2011-06-10 49 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