a crux about nil test in ruby code -
i have crux in ruby code(excerpt this page):
#!/usr/bin/env ruby class megagreeter attr_accessor :names #create object def initialize(names = "world") @names = names end # hi def say_hi if @names.nil? puts "..." elseif @names.respond_to?("each") # @names list of kind,iterate! @names.each |name| puts "hello #{name}!" end else puts "hello #{@names}!" end end # bye def say_bye if @names.nil? puts "..." elseif @names.respond_to?("join") puts "goodbye #{@names.join(",")}. come soon." else puts "goodbye #{@names}. come soon." end end end if __file__ == $0 mg = megagreeter.new mg.say_hi mg.say_bye # change name "zeke" mg.names = "zeke" mg.say_hi mg.say_bye # change name array of names mg.names = ["albert", "brenda", "charles", "dave", "engelbert"] mg.say_hi mg.say_bye # change nil mg.names = nil mg.say_hi mg.say_bye end
when run script ruby command, prints:
hello world! goodbye world. come soon. hello zeke! goodbye zeke. come soon. hello ["albert", "brenda", "charles", "dave", "engelbert"]! goodbye ["albert", "brenda", "charles", "dave", "engelbert"]. come soon. ... ri20min.rb:15:in `say_hi': undefined method `elseif' #<megagreeter:0x00000001a2d4a0 @names=nil> (nomethoderror) ri20min.rb:54:in `<main>'
i want check whether variable nil.
if @names.nil?
but error frustrated me! seems nil object has not nil method! how can amend code run correctly.
there no elseif
in ruby, there elsif
.
Comments
Post a Comment