【问题标题】:Hash.assoc undefined method 'assoc'Hash.assoc 未定义的方法'assoc'
【发布时间】:2011-06-11 07:43:08
【问题描述】:

当我打开 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

虽然这段代码取自http://ruby-doc.org/core/classes/Hash.html#M000760 我做错了什么?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 2013-06-11
      • 2010-12-30
      • 2019-12-25
      • 2021-07-25
      • 2019-06-20
      相关资源
      最近更新 更多