2011-06-10 34 views
0

,當我打開IRB並粘貼Hash.assoc未定義的方法「assoc命令」

h = {"colors" => ["red", "blue", "green"], 
     "letters" => ["a", "b", "c" ]} 
h.assoc("letters") #=> ["letters", ["a", "b", "c"]] 
h.assoc("foo")  #=> nil 

進去我總是得到消息:

NoMethodError: undefined method `assoc' for {"letters"=>["a", "b", "c"], "colors"=>["red", "blue", "green"]}:Hash 
from (irb):3 
from :0 

儘管此代碼是從http://ruby-doc.org/core/classes/Hash.html#M000760 採取了我是什麼做錯了?

回答

4

Hash#assoc是一個Ruby 1.9的方法,在Ruby 1.8(您可能正在使用)中不提供。

如果你想同樣的結果,你可以只是做

["letters", h["letters"]] 
# => ["letters", ["a", "b", "c"]] 

你可以在類似的行爲在打補丁的Ruby 1.8太:

class Hash 
    def assoc(key_to_find) 
    if key?(key_to_find) 
     [key_to_find, self[key_to_find]] 
    else 
     nil 
    end 
    end 
end