标签:style blog http color art html
#!/usr/bin/env ruby class 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 end end if __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_bye end
这短代码是ruby初学者都会接触的代码,具体参照二十分钟教你学Ruby。
日文链接https://www.ruby-lang.org/zh_tw/documentation/quickstart/4/
中文链接http://tech.it168.com/d/2007-09-04/200709041111532.shtml
标签:style blog http color art html
原文地址:http://www.cnblogs.com/yulander1314/p/3831972.html