1

我想知道为什么当我进入这个...;

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 

为什么它返回假?它不应该返回true吗?说价值实际上是零?此外,它将 nil 值替换为 false 值。谁能给新手解释一下?

2.0.0-p247 :049 > @possible_places
 => {:a1=>false, :a2=>nil, :a3=>nil} 
2.0.0-p247 :050 > @possible_places[:a1]
 => false 
4

2 回答 2

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?。在顶层selfmain,您在其上调用方法#nil?。由于main对象不是nil,因此false值已分配给您的哈希键:a1。您应该如下调用它:

self.nil? # => false
@possible_places = {:a1=>nil, :a2=>nil, :a3=>nil} 
@possible_places[:a1] # => nil
@possible_places[:a1].nil? # => true
于 2013-10-16T16:51:05.670 回答
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
于 2013-10-16T17:34:44.960 回答