標籤:style blog http color art html
#!/usr/bin/env rubyclass MegaGreeter attr_accessor :names # 初始化這個物件 def initialize(names = "World") @names = names end # 向每個人說 hi def say_hi if @names.nil? puts "..." elsif @names.respond_to?("each") # @names 是可以迭代的陣列容器 @names.each do |name| puts "Hello #{name}!" end else puts "Hello #{@names}!" end end # 向每個人說 bye def say_bye if @names.nil? puts "..." elsif @names.respond_to?("join") # 用逗號將陣列中的元素串接成一個字串 puts "Goodbye #{@names.join(", ")}. Come back soon!" else puts "Goodbye #{@names}. Come back soon!" end endendif __FILE__ == $0 mg = MegaGreeter.new mg.say_hi mg.say_bye # 變更成 "Zeke" mg.names = "Zeke" mg.say_hi mg.say_bye # 變更成一個名字的陣列 mg.names = ["Albert", "Brenda", "Charles", "Dave", "Engelbert"] mg.say_hi mg.say_bye # 變更成 nil mg.names = nil mg.say_hi mg.say_byeend
這短代碼是ruby初學者都會接觸的代碼,具體參照二十分鐘教你學Ruby。
日文連結https://www.ruby-lang.org/zh_tw/documentation/quickstart/4/
中文連結http://tech.it168.com/d/2007-09-04/200709041111532.shtml