开始我的Ruby之旅,写下学习笔记,是针对那些有其他OO语言经验的人写的,可以来看下神奇的Ruby。
第一个sample! 初次见面。
#!/usr/bin/env ruby
class MegaGreeter
attr_accessor :names
# Create the object
def initialize(names = "World")
@names = names
end
# Say hi to everybody
def say_hi
if @names.nil?
puts ""
else
if @names.respond_to?("each")
# @names is a list of some kind, iterate!
@names.each do |name|
puts "Hello #{name}!"
end
else
puts "Hello #{@names}!"
end
end
end
# Say bye to everybody
def say_bye
if @names.nil?
puts ""
else
if @names.respond_to?("join")
# @join the list elements with commas
puts "Goodbye #{@names.join(",")}. Come back soon!"
else
puts "Goodbye #{@names}!"
end
end
end
end
if __FILE__ == $0
mg = MegaGreeter.new
mg.say_hi
mg.say_bye
#Change name to be "zeke"
mg.names = "Jaylee"
mg.say_hi
mg.say_bye
#Change the name an array of names
mg.names = ["Albert", "Brenda", "Coderlee"]
mg.say_hi
mg.say_bye
#Change to nil
mg.names = nil
mg.say_hi
mg.say_bye
end
class MegaGreeter
attr_accessor :names
# Create the object
def initialize(names = "World")
@names = names
end
# Say hi to everybody
def say_hi
if @names.nil?
puts ""
else
if @names.respond_to?("each")
# @names is a list of some kind, iterate!
@names.each do |name|
puts "Hello #{name}!"
end
else
puts "Hello #{@names}!"
end
end
end
# Say bye to everybody
def say_bye
if @names.nil?
puts ""
else
if @names.respond_to?("join")
# @join the list elements with commas
puts "Goodbye #{@names.join(",")}. Come back soon!"
else
puts "Goodbye #{@names}!"
end
end
end
end
if __FILE__ == $0
mg = MegaGreeter.new
mg.say_hi
mg.say_bye
#Change name to be "zeke"
mg.names = "Jaylee"
mg.say_hi
mg.say_bye
#Change the name an array of names
mg.names = ["Albert", "Brenda", "Coderlee"]
mg.say_hi
mg.say_bye
#Change to nil
mg.names = nil
mg.say_hi
mg.say_bye
end