Google自訂搜尋

目前分類:Ruby console (17)

瀏覽方式: 標題列表 簡短摘要

TWSMSR是一個搭配台灣簡訊(http://twsms.com)使用的簡訊傳送Library

TWSMSR的前身SMSender已經停止維護,將直接改由這個名稱與版本重新出發!

網址在:http://github.com/cfc/twsmsr

使用方式:

require 'twsmsr'
t = TWSMSR.new(username, password) # 帳號密碼請自己申請。
resp = t.send(tel, message) # 取得回應,如果resp是負的,表示有錯誤。如果resp大於0則那是Message ID,可以用t.query查詢狀態。
puts t.query # 查詢錯誤訊息
puts t.message_id # 取得Message ID
t.message_id = "123456" # 設定Message ID
puts t.query

 

有任何疑問歡迎寄信或留言,原始碼可上Github查看

hechian 發表在 痞客邦 留言(0) 人氣()

今天剛看到生活+釋出API(其實早就釋出了,API網址:http://tw.developer.yahoo.com/lifestyle_api.html)後,就開始把NetBeans打開來寫程式了XD
現在RubyForge的專案還沒開,倒是GoogleCode的已經開了(網址:http://code.google.com/p/yahoo-lifetype-api/)
程式是BSD授權,忘記怎樣包裝Gem檔,等到哪天想起來再包XD
程式使用範例(列出生活+的分類):
#!/usr/bin/env ruby
APPID = "NhYX9XjV34FPxdq7zD8T7wwc4QGI5VWu_48NHh03zbPYUfPpcWrpZzhcVDKFQsH9dQ--"
require 'lifetype'
require 'rexml/document'
include REXML

puts "獲取生活+類別中... 請稍後"
doc = Document.new(LifeType::Class.new(APPID).listClasses)
puts "獲取類別結束"
puts "類別總數: " + doc.get_elements("//rsp/ClassList")[0].attribute("count").to_s
puts "列出類別中... 請稍後"
doc.elements.each("//rsp/ClassList/Class") do |ele|
puts "ID: #{ele.attributes["id"]} -- #{ele.get_elements("Title")[0].text}"
end
puts "列出類別結束"
很簡單的就可以使用了,還有doc喔!
有Bug可以丟到GoogleCode的Issues或者丟到我信箱內
謝謝^^
Update: 2008/04/25 09:15
  現在可以從我的ShareMe抓0.3版了,請按我

hechian 發表在 痞客邦 留言(0) 人氣()

我把原始碼放在妹尬阿撲落得上面了
UTF-8ANSI碼兩種編碼版本
參考這篇文章撰寫的:[台灣論壇]  測試你的手機號碼是吉是凶
晚點再放上執行檔下載點...

hechian 發表在 痞客邦 留言(0) 人氣()

有鑒於某台主機的DNS常常掛掉.. 所以就寫了這個小程式..

while true
  `ps aux | grep named`.split("\n").each{|line|
    user, pid, cpu, mem, vsz, rss, tty, stat, start, time, *command = line.split("\s")
    flag = true if command[0] == "/usr/sbin/named"
    `/etc/init.d/named start` unless flag
  }
  sleep 300
end

hechian 發表在 痞客邦 留言(0) 人氣()

這個Library搭配http://www.twsms.com才可以使用喔!
有任何問題可以直接回這篇文章,或者寫信問我,我信箱是Gmail的,帳號跟我的這個部落格帳號一樣

我先說用法好了:
require 'twsms'
sms = TWSMS.new(username, password) # 帳號密碼
sms.sendSMS(mobile, message) # mobile: 目標手機號碼  message: 要傳的訊息
原始碼:
=begin
  == Information ==
  === Copyright: Apache 2.0
  === Author: CFC < zusocfc@gmail.com >
  === Prog. Name: TWSMS lib
  === Version: 0.1
  == Introduction ==
    TWSMS(Taiwan SMS)
    TWSMS is a SMS sender, it must use with http://www.twsms.com.
    There has no any library for the SMS system in Taiwan. So, I just coded this and release this version.
    This version just support for sending SMS.
  == Featured ==
   
  == Using TWSMS ==
    It just support for standalone class now.
    require it before you use.
  === Using TWSMS by standalone class
    require 'twsms'
    sms = TWSMS.new('username', 'password')
    sms.sendSMS('09xxxxxxxx', 'Hi, there! TWSMS library is so easy to use!')
    sms.sendSMS('09xxxxxxxx', 'Send SMS with options',
        :popup => 1,
        :type => "now",
        :mo => "Y")
=end

%w|uri cgi net/http|.each{|r| require r}

class TWSMS
  def initialize(username, password)
    @uname, @upwd = username, password
    @options = {
      :type => "now", # Sending type: now, vld
      :popup => "",
      :mo => "Y".upcase,
      :vldtime => "86400",
      :modate => "",
      :dlvtime => "",
      :wapurl => "",
      :encoding => "big5"
    }
   
    @errors = {
      -1.to_s.to_sym => "Send failed",
      -2.to_s.to_sym => "Username or password is invalid",
      -3.to_s.to_sym => "Popup tag error",
      -4.to_s.to_sym => "Mo tag error",
      -5.to_s.to_sym => "Encoding tag error",
      -6.to_s.to_sym => "Mobile tag error",
      -7.to_s.to_sym => "Message tag error",
      -8.to_s.to_sym => "vldtime tag error",
      -9.to_s.to_sym => "dlvtime tag error",
      -10.to_s.to_sym => "You have no point",
      -11.to_s.to_sym => "Your account has been blocked",
      -12.to_s.to_sym => "Type tag error",
      -13.to_s.to_sym => "You can't send SMS message by dlvtime tag if you use wap push",
      -14.to_s.to_sym => "Source IP has no permission",
      -99.to_s.to_sym => "System error!! Please contact the administrator, thanks!!"
    }
    @args = []
    @url ||= "http://api.twsms.com/send_sms.php?"
    @url += "username=" + @uname
    @url += "&password=" + @upwd
  end
 
  def sendSMS(mobile, message, opt={})
    @options[:mobile], @options[:message] = mobile, message
    @options.merge!(opt).each{|k, v| @args << k.to_s + "=" + CGI::escape(v.to_s)}
    @url += "&" + @args.join("&")
    self.chk_val
    chk_errors(Net::HTTP.get(URI.parse(@url)))
  end
 
  def chk_val
    @options[:dlvtime] = "" unless @options[:type] == "dlv"
    @options[:wapurl] = "" if @options[:type] != ("push" && "upush")
  end
 
  def chk_errors(resp)
    resp = resp.split("=")[1]
    if @errors.has_key?(resp.to_s.to_sym)
      puts "==========", "Error!! Message: ", @errors[resp.to_s.to_sym]
    else
      puts "==========", "Message has been send! Your message id is: " + resp.to_s
    end
  end
 
  protected :chk_val
end
晚點丟到Google Code Hosting上去...

Updated:
TWSMS on Google Code Hosting: http://code.google.com/p/twsms/
SMSender on RubyForge: http://rubyforge.org/projects/smsender/

hechian 發表在 痞客邦 留言(2) 人氣()

class Array
  def which_long?
    # Version 1.0
    # Coded by CFC < zusocfc  @ gmail . com >
    # PLEASE DO NOT REMOVE THE COMMENT OF THIS FUNCTION, THANKS A LOT.
    # Usage:
    #   ['a', 'ab', 'abc' 1234].which_long?
    #   => 1234
    self.size.times{|i| self[i]=self[i].to_s}
    max, long = 0, String.new
    self.each{|item| item.size > max ? (max = item.size; long = item) : next}
    long
  end
end

以上是原始碼,使用方式如下:

puts ['a', 'ab', 'abc', 1234].which_long?
=> 1234

授權還沒定,不過大家還是可以拿去使用:P
請不要拿掉註解.. 謝謝

hechian 發表在 痞客邦 留言(0) 人氣()

版本1可以不用寫群組名稱,但是程式碼好醜ˊˋ
版本2必須要有群組名稱,適用於學校(?)

版本1下載
版本2下載

版本1:

#!/usr/bin/env ruby
File.open(ARGV[0]) do |file|
  while a = file.gets
    a = a.chomp.split(/ /)
    print "username => #{a[0]} ", "password => #{a[1]} ", "group => #{a[2]}", "\n"
    a[2].nil? ? `useradd -m #{a[0]}` : `useradd -m -G #{a[2]} #{a[0]}`
    `echo #{a[0]}:#{a[1]} | chpasswd`
  end
end
exec "pwconv"

使用者清單寫法:

  帳號 密碼 群組

版本2:

#!/usr/bin/env ruby
require 'yaml'
YAML.load_file(ARGV[0]).each{ |grp|
  grp.each{ |usr|
    usr.each{ |i|
      info = i.chomp.split(/ /)
      `useradd -m -G #{grp[0]} #{info[0]}`
      `echo #{info[0]}:#{info[1]} | chpasswd`
    }
  }
}
`pwconv`

使用者清單寫法:
grp1:
  - usr1 pwd1
  - usr2 pwd2
grp2:
  - usr3 pwd3
  - usr4 pwd4
grp3:
  - usr5 pwd5
  - usr6 pwd6
使用方式都是:
./account list

程式授權.. 隨便啦

hechian 發表在 痞客邦 留言(0) 人氣()

此版本尚未支援 影片代碼 功能

原始碼如下:
require 'rubygems'
require 'mechanize'

class HEMiDEMi
  def initialize(username="", password="")
    agent = WWW::Mechanize.new{}
    f = agent.get("http://www.hemidemi.com/member/signin_form").forms[1]
    f["member[username]"], f["member[password]"] = username, password
    f.submit
    @agent = agent
    @base_url = "http://www.hemidemi.com"
    @new_path = "/user_bookmark/new"
  end
 
  def run(file)
    File.open(file) do |f|
      f.readlines.each do |frl|
        next if frl[0].chr == "#"
        title, url, quotes, description, t_s, g_s = frl.split(/\t/)
        self.add({
          "title" => title,
          "url" => url,
          "quotes" => quotes,
          "description" => description,
          "tag_string" => t_s,
          "group_string" => g_s
        })
      end
    end
  end
 
  def add(qs)
    f = @agent.get(@base_url+@new_path).forms[1]
    qs.each do |k, v|
      puts "Add: #{k} as #{v}"
      f["user_bookmark[#{k}]"] = v
    end
    f.fields.each do |x| puts x.name + " => " + x.value end
    f.submit
  end

end
puts "請輸入HEMiDEMi使用者帳號跟密碼(用空格分開):"
ud = gets.chomp.split(/ /)
hemidemi = HEMiDEMi.new(ud[0], ud[1])
puts "請輸入檔案位置,不輸入則預設值為當前目錄下的bms.txt:"
path = gets.chomp
path == "" ? hemidemi.run("bms.txt") : hemidemi.run(path)


另外,bms.txt檔案內容是:

# 欄位說明:
#   title\turl\tquotes\tdescription\ttag_string\tgroup_string
#   標題<tab>網址<tab>引述<tab>說明<tab>標籤<tab>群組
#   <tab>:按一次Tab鍵
# 底下是範例:
HEMiDEMi    http://www.hemidemi.com        HEMiDEMi共享書籤    hemidemi    test ruby_and_ror

說明:

請先建立好bms.txt或者其他檔案名稱的純文字檔
欄位寫的很清楚,就是:標題<tab>網址<tab>引述<tab>說明<tab>標籤<tab>群組
請記得一定要用tab來分隔,建議用Windows內建的記事本來編寫
如果想要空掉某些欄位,則該欄位不填直接按下tab鍵即可,看範例就可以知道 (範例沒有寫上引述)

程式授權:MIT
程式所需套件:rubygems、mechanize跟mechanize之所需套件
mechanize安裝方式:
  請先確定有rubygems,如果沒有請到RubyForge下載安裝
  打開命令提示字元或者終端機,輸入:
    gem i mechanize -y
  如果有要你選版本的話,Windows使用者請選擇(mswin32)版本,而其他作業系統請選(ruby)版本
程式原始碼下載:
Windows (Big5)
Linux (UTF-8)

hechian 發表在 痞客邦 留言(0) 人氣()

原始碼在這邊:

require 'rubygems'
require 'mechanize'

class HEMiDEMi
  def initialize(username="", password="")
    agent = WWW::Mechanize.new
    f = agent.get("http://www.hemidemi.com/member/signin_form").forms[1]
    f["member[username]"], f["member[password]"] = username, password
    f.submit
    @agent = agent
    @base_url = "http://www.hemidemi.com"
    @new_path = "/user_bookmark/new"
  end
 
  def add(qs)
    f = @agent.get(@base_url+@new_path).forms[1]
    qs.each do |k, v|
      f["user_bookmark[#{k}]"] = v
    end
    f.submit
  end

end
=begin
qs = {
  "title" => title,
  "url" => url,
  "quotes" => quotes,
  "description" => desc,
  "tag_string" => t_s,
  "group_string" => g_s,
  "embed" => embed
}
=end

qs = {
  "title" => "G00g13",
  "url" => "google.com"
}

hemidemi = HEMiDEMi.new("", "").add(qs)


目前這個版本只是雛型.. 還不能夠用來大量新增!
簡單介紹一下...

qs = {
  "title" => title,
  "url" => url,
  "quotes" => quotes,
  "description" => desc,
  "tag_string" => t_s,
  "group_string" => g_s,
  "embed" => embed
}

qs是一個Hash,我只講其中幾個
quotes:代表的是"引述"
description:代表的是"說明"
embed:代表的是影片代碼

hechian 發表在 痞客邦 留言(0) 人氣()

心情不好,就把這給寫了出來
莊千慧,這東西我想應該可以多少幫助妳一點=  =

說明:
  這程式會將指定檔案內的英文單字印出且輸出Yahoo奇摩字典針對該單字解說的連結。
  假設我有一個單字是below,將會產生以下網址:
  http://tw.dictionary.yahoo.com/search?ei=UTF-8&p=below
  我也不知道這工具有沒有派上用場的時候.. 加減用吧.. 應該搭配Rails的..

Below is the source code:

print "Please select a file:\n> "; file = gets.chomp
IO.readlines(file).each do |item|
  item = item.gsub(/ /, "+")
  str = "http://tw.dictionary.yahoo.com/search?ei=UTF-8&p=#{item}"
  puts str
  File.new("file2.txt", "a").write(str)
end

hechian 發表在 痞客邦 留言(0) 人氣()

請在命令提示字元或者虛擬終端機下執行以下指令(請記得安裝Ruby)

ruby -e "32.times{|y|print\" \"*(31-y);(y+1).times{|x|print\" #{~y&x==0?\"A\":\".\"}\"};puts}"
 

hechian 發表在 痞客邦 留言(2) 人氣()

這次的這個版本,則是將 "最新書籤(整個網站)", "使用者最新書籤", "群組最新書籤" 3個合併囉
也就是說,使用者只要下參數,就可以抓到資訊了!
參數:

$ ruby ./recent.rb [要抓的資訊] [要顯示的書籤量] [名稱]

* 整個程式省略掉參數的話,就是整個網站的最新書籤

要抓的資訊:
  0: 整個網站的最新書籤
  1: 使用者最新書籤
  2: 群組最新書籤

這個版本還沒有Method overload... 因此沒有辦法省略掉其中的幾個參數..
未來版本會修正這個問題
程式碼如下:

#!/usr/bin/env ruby
# Code by CFC Zuso Security
# # Taiwan Ruby Users Group: http://www.ruby.oss.tw/
# # Rails Taiwan: http://www.rubyonrails.org.tw/
#
# Hemidemi bookmarks loader: Ver. 0.0.0.2 Beta
#
#==========
#
# 1. Recent: http://www.hemidemi.com/rss/bookmark/recent.xml
# 2. User's recent: http://www.hemidemi.com/rss/user/#{@usr_name}/bookmark/recent.xml
# 3. Group's recent: http://www.hemidemi.com/rss/group/#{@grp_name}/bookmark/recent.xml
#
#==========
#

require 'rexml/document'
require 'open-uri'
include REXML

class Recent
  def initialize(opt, count, name)
    case opt.to_i
      when 0
        @url = "http://www.hemidemi.com/rss/bookmark/recent.xml"
      when 1
        @url = "http://www.hemidemi.com/rss/user/#{name}/bookmark/recent.xml"
      when 2
        @url = "http://www.hemidemi.com/rss/group/#{name}/bookmark/recent.xml"
      else
        @url = "http://www.hemidemi.com/rss/bookmark/recent.xml"
    end
    @channel = @channel || {}
    @items = []
    if count == nil
      @count = 6
    else
      @count = count.to_i
    end
  end

  def run
    load_in
    show
  end

  def load_in
    open(@url) do |f|
      xml = Document.new(f.read)

      xml.elements.each("*/channel") do |chnl|
        @channel["name"] = chnl.elements["description"].text
        @channel["link"] = chnl.elements["link"].text
      end

      xml.elements.each("*/channel/item") do |item|
        itm = {}
        itm["title"] = item.elements["title"].text
        itm["description"] = item.elements["description"].text
        itm["link"] = item.elements["link"].text
        itm["creator"] = item.elements["dc:creator"].text
        @items << itm
      end
    end
  end

  def show
    line = "=" * 100
    puts @url
    puts line
    puts "#{@channel["name"]} [ #{@channel["link"]} ]"
    puts "共有#{@items.size}個書籤"
    puts line
    @count = @items.size if @items.size < @count
    @count.times { |cnt|
      puts "張貼者:#{@items[cnt]["creator"]} [ http://www.hemidemi.com/user/#{@items[cnt]["creator"]}/home ]"
      puts "標題:#{@items[cnt]["title"]}"
      puts "網址:#{@items[cnt]["link"]}"
      puts "敘述:#{@items[cnt]["description"]}"
      puts "-"*10
    }
    puts line
  end
  public :run
  private :load_in, :show
end

rss = Recent.new(ARGV[0], ARGV[1], ARGV[2])
rss.run

下載點:
http://stmail.tajen.edu.tw/~593092514/recent.rb

hechian 發表在 痞客邦 留言(0) 人氣()

哇哇哇
http://flickr.tw的站長推出這麼棒的Hemidemi hacking...
只是小弟遜咖,沒辦法像他那樣>"<
好吧.. 我只好寫個個人用的小工具

這個程式是適用於群組的,一般來說群組都會有最新書籤,而這個是將最新書籤印出來的..
程式只能跑在純文字模式下.. 輕巧咩~另外網管如果沒有在管沒有X Window的主機時,也可以用這個拉!
Usage:
$ ./grp_recent.rb group_name [count]
Options:
    * group_name: 沒錯!就是群組名稱!
    * count: 可省略參數,用於顯示幾個書籤(從最新的開始算起,預設是6個)

程式碼如下:
#!/usr/bin/env ruby
# Code by CFC Zuso Security
# Taiwan Ruby Users Group: http://www.ruby.oss.tw/
# Rails Taiwan: http://www.rubyonrails.org.tw/
#
require 'rexml/document'
require 'open-uri'
include REXML

class Recent
  attr_accessor :grp_name, :channel, :items

  def initialize(grp_name, count)
    @grp_name = grp_name
    @url = "http://www.hemidemi.com/rss/group/#{@grp_name}/bookmark/recent.xml"
    @channel = @channel || {}
    @items = []
    if count == nil
      @count = 6
    else
      @count = count.to_i
    end
  end

  def run
    load_in
    show
  end
  def load_in
    open(@url) do |f|
      xml = Document.new(f.read)

      xml.elements.each("*/channel") do |chnl|
        @channel["name"] = chnl.elements["description"].text
        @channel["link"] = chnl.elements["link"].text
      end

      xml.elements.each("*/channel/item") do |item|
        itm = {}
        itm["title"] = item.elements["title"].text
        itm["description"] = item.elements["description"].text
        itm["link"] = item.elements["link"].text
        itm["creator"] = item.elements["dc:creator"].text
        @items << itm
      end
    end
  end

  def show
    puts "="*10
    puts "群組:#{@channel["name"]} [ #{@channel["link"]} ]"
    puts "共有#{@items.size}個書籤"
    puts "="*10
    @count = @items.size if @items.size < @count
    @count.times { |cnt|
      puts "張貼者:#{@items[cnt]["creator"]} [ http://www.hemidemi.com/user/#{@items[cnt]["creator"]}/home ]"
      puts "標題:#{@items[cnt]["title"]}"
      puts "網址:#{@items[cnt]["link"]}"
      puts "敘述:#{@items[cnt]["description"]}"
      puts "*"*10
    }
    puts "="*10
  end
  public :run
  private :load_in, :show
end

rss = Recent.new(ARGV[0], ARGV[1])
rss.run


下載點:http://stmail.tajen.edu.tw/~593092514/grp_recent.rb

hechian 發表在 痞客邦 留言(0) 人氣()

原文章轉至:http://lightyror.blogspot.com/2006/09/ruby-syntax-suger.html
 

剛剛正在寫一個計算 apache 有多少 process 的 Ruby Script


`ps auxw | grep apache `.split("\n").each do |line|
user,pid,cpu,mem,vsz,rss,tty,stat,start,time,command = line.split("\s")
process_count += 1 if command == '/usr/sbin/apache'
end


注意這一段
user,pid,cpu,mem,vsz,rss,tty,stat,start,time,command = line.split("\s")
寫完之後,興奮之情仍然無法消去
平行 asignment 雖然被人稱為是 syntax suger
但是這樣的 syntax suger 可以很有效的幫助 programmer 整理邏輯
而這樣的寫法,以後我要做什麼擴充像是 user = 'abc' 都很方便
也不用重新查一次 ps 的排列順序

誰說 syntax suger 不重要的


==========
底下是心得
==========

嗯..
簡單的說
我可以偵測CPU使用率,過高的就`kill -9 #{pid}`
對於系統管理員來說,無疑是極大的方便阿!!

hechian 發表在 痞客邦 留言(0) 人氣()

昨晚又失眠了...
唉...

然後順便想著...
In Ruby, integer can use method 'chr' to convert to the character
but If I want to convert charactor to integer, how can I do?

我記得以前有用過,可是我忘了
一直找不到那個method可以轉換
所以剛剛上了irc://irc.freenode.net/ #ruby-lang
問了一下...
一開始,我並不知道有這method... 所以我自己寫了個
But I don't know how can I get the value...

Following is the chatting log in the channel...

zusocfc: Hi, all
zusocfc: Excuse me.. I want to do a meta programming...
zusocfc: I want to re-define the Integer class, add a method named "asc"
kmeyer: class Integer; def asc;
zusocfc: And I don't know how to get the integers
zusocfc: kmeyer: I know that, I mean I want to do like..
zusocfc: kmeyer:  puts 65.asc # Output "A"
kmeyer: oh.
kmeyer: You want chr
kmeyer: 65.chr # "A"
zusocfc: Orz.. wait
zusocfc: =  ="
zusocfc: puts "A".asc # Output 65
kmeyer: "A".ord
zusocfc: ....
kbrooks: no
kmeyer: err
kmeyer: wait
kbrooks: "A"[0]
kmeyer: "A"[0]
kmeyer: or ?A
zusocfc: ha! Thanks a lot :D
kmeyer: no prob
zusocfc: but.. If I want to add a method for practice like that, how can I do?
zusocfc: kmeyer: uh... it return 0
zusocfc: returned*
kmeyer: "a".asc ?
kmeyer: then swap out [0] for self[0]
zusocfc: kmeyer: got it.. thanks :D
zusocfc: kmeyer: excuse me... I have a problem... now there has a code "65.chr", how chr gets the value '65'?
kmeyer: it's smart :P
kmeyer: err
zusocfc: kmeyer: err...
kmeyer: chr is a method on Fixnum
kmeyer: self
kmeyer: but it's actually in C
zusocfc: kmeyer: OK!! Thank you :D

ya~ you can use "self" to get the value, and '?' or '[0]' can get the ASCII code of the character!
But, it could not be use when I input a string...
So... I have to write a member funtion for class String that convert each character in a string to ascii code...
Following is the source code...

class String

  def each_asc
    ascii = Array.new
    self.size.times do |c|
      ascii[c] = self[c]
    end
    ascii
  end

end


Usage:

puts "ABCD".each_asc

It will output:
65
66
67
68

hechian 發表在 痞客邦 留言(0) 人氣()

呼.. 為了EasyURL,剛剛花了點時間自己搞了個產生亂碼的程式
程式碼在這邊
想看的請用Shift + 左鍵點選(或者右鍵開新視窗;如果是Firefox使用者建議使用”用新分頁開啟”)

程式碼修正:
心得:被GSR用一行嗆明.. 我真的該檢討>"<

class CA
  def generate times=1
    times = 1 if times <= 0
    return (1..times.to_i).to_a.collect{|x| (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a)[rand(62)]}.join 
  end
 
  def gen times=1
    generate times
  end
end


hechian 發表在 痞客邦 留言(0) 人氣()

嗯.. 這邊用Ruby寫一個小程式.. 
程式內容是定義一個類別Beast,然後再定義一個類別Bear去繼承Beast
看下面吧↓

#!/usr/local/bin/ruby
class Beast
def initialize( name )
  p "A monster was born"
  @name = name
end
def roar
  p "Wow~ I'm "+@name
end
end

class Bear < Beast #繼承Beast
def initialize( name )
  super (name) #因為name被重新定義,Beast中的name就被破壞,用super將Beast的name重新呼叫一次
  p "I'm a bear"
end
end

myBear=Bear.new("CFC")
myBear.roar


hechian 發表在 痞客邦 留言(0) 人氣()