Ruby Hash.assoc未定义方法';协会';

Ruby Hash.assoc未定义方法';协会';,ruby,Ruby,当我打开IRB并粘贴 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 {"lette

当我打开IRB并粘贴

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
尽管此代码取自 我做错了什么?

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
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