我想知道为什么当我进入这个......;
2.0.0-p247 :046 > @possible_places
=> {:a1=>nil, :a2=>nil, :a3=>nil}
2.0.0-p247 :047 > @possible_places[:a1]
=> nil
2.0.0-p247 :048 > @possible_places[:a1]=nil?
=> false
为什么会返回false?它不应该归还吗?说这个值实际上是零? 此外,它将nil值替换为false值。有人可以向newb解释吗?
2.0.0-p247 :049 > @possible_places
=> {:a1=>false, :a2=>nil, :a3=>nil}
2.0.0-p247 :050 > @possible_places[:a1]
=> false
答案 0 :(得分:2)
原因如下:
self.nil? # => false
@possible_places = {:a1=>nil, :a2=>nil, :a3=>nil}
@possible_places[:a1] # => nil
@possible_places[:a1]=nil? # => false
在@possible_places[:a1]=nil?
行中,您在顶级对象#nil?
上调用了main
。@possible_places[:a1]=nil?
- 它实际上意味着@possible_places[:a1]=self.nil?
。在顶层{ {1}} self
,您调用了main
方法。由于#nil?
对象不是main
,因此nil
值已分配给密钥你的Hash的false
。你应该如下所示:
:a1
答案 1 :(得分:1)
您认为它应该返回“true”表示您使用的是错误的运算符。一个等号(=)用于设置左侧值的值。不要考验平等。如果要测试相等性,请使用==运算符。
@possible_places[:a1] == 1
# Test if @possible_places[:a1] is equal to 1 (False)
@possible_places[:a1] = 1
# Set possible_places[:a1] to 1 and return 1
@possible_places[:a1] == 1
# Test if @possible_places[:a1] is equal to 1 (True)
p nil? #=> false (See Arup Rakshit's answer to understand why)
@possible_places[:a1]=nil? # Set value to nil? or false, and return that value.
那么,为了测试你的哈希值是否为零,你需要做以下其中一种吗?
@possible_places[:a1]=nil # Set hash to nil
@possible_places[:a1].nil? # true
@possible_places[:a1] == nil # true