我从昨天开始学习Ruby。以下是我的疑问:
class MegaGreeter
attr_accessor :names
def intialize(names="World!")
@names = names
end
def say_test
if @names.nil?
puts "nil test..."
end
end
end
megaGreeter = MegaGreeter.new
megaGreeter.say_test // Here showing ouput as "nil test..."
起初我只是assuming 'nil' almost like 'null' in java
。但在上述情况下,我的假设似乎是错误的。
我不明白为什么在if @names.nil returning as TRUE
以上?,因为@names will have a value "World!"
所以,@ names如何视为null?
我已经搜索了“nil
”,但我真的没有清楚地了解它。
答案 0 :(得分:5)
你有一个错字。 #intialize
应为initialize
。
见,
class MegaGreeter
attr_accessor :names
def initialize(names = "World!")
@names = names
end
def say_test
if @names.nil?
puts "nil test..."
else
puts "@names is not holding nil"
end
end
end
megaGreeter = MegaGreeter.new
megaGreeter.say_test # => @names is not holding nil
megaGreeter = MegaGreeter.new(nil)
megaGreeter.say_test # => nil test...