看到ruby的程序,学习了20分钟的教程:
https://www.ruby-lang.org/en/documentation/quickstart/ 明白了ruby运行的大概情况。
下面是我整理的代码,详细解释在英文教程里,ruby里面的end很多,要细心处理:
Ruby语言:
#!/usr/bin/env ruby
num_events = ARGV[0].to_i
class MegaGreeter
attr_accessor :names
def initialize(names="World")
@names = names
end
def say_hi
if @names.nil?
puts "..."
elsif @names.respond_to?("each")
# @names is a iterator
@names.each do |name|
puts "Hello #{name}!"
end
else
puts "Hi #{@names} !"
end
end
def say_bye
if @names.nil?
puts "..."
elsif @names.respond_to?("join")
puts "Goodbye #{@names.join(", ")}. Come back soon!"
else
puts "Bye #{@names}, come back soon."
end
end
end
if __FILE__ == $0
puts MegaGreeter.instance_methods(false)
mg = MegaGreeter.new
mg.say_hi
mg.say_bye
puts mg.respond_to?("names=")
mg.names="Betty"
mg.say_hi
mg.say_bye
mg.names = ["Albert", "Brenda", "Charles",
"Dave", "Engelbert"]
mg.say_hi
mg.say_bye
mg.names = nil
mg.say_hi
mg.say_bye
end
阅读(1092) | 评论(0) | 转发(0) |