FlyingFoX
FlyingFoX

Reputation: 3509

Hash.assoc undefined method 'assoc'

When i open IRB and paste

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

into it i always get the message:

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

although this code is taken from http://ruby-doc.org/core/classes/Hash.html#M000760 What am i doing wrong?

Upvotes: 0

Views: 422

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124449

Hash#assoc is a Ruby 1.9 method, and is not available in Ruby 1.8 (which you're probably using).

If you wanted the same results, you could just do

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

You could patch in similar behavior in Ruby 1.8 too:

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

Upvotes: 4

Related Questions