2013-10-16 84 views
1

我想知道爲什麼當我輸入這個...;爲什麼我的散列值更改爲false

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?它不應該返回真實?說這個價值實際上是零? 此外,它用這個假值替換零值。任何人都可以請給newb解釋一下嗎?

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

請使用恰當的語言標記。 – NPE

回答

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? method.As main對象不是nil,從而false值已分配給您的Hash.You應該如下調用它的關鍵:a1

self.nil? # => false 
@possible_places = {:a1=>nil, :a2=>nil, :a3=>nil} 
@possible_places[:a1] # => nil 
@possible_places[:a1].nil? # => true 
+0

謝謝你的回答。我仍然對你說的調用頂層對象感到困惑,但我確信你正確的道路上,所以我會檢查你的答案! – user2817130

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 
相關問題