Undefined method 'to_h' on Ruby array
Solution 1
The to_h
method is only available in Ruby version 2.1 or higher.
Check the release notes here
http://pivotallabs.com/ruby-2-1-0-changes-of-note/
Solution 2
Yes, it's not supported for lower version than Ruby 2.1, If you are looking for alternative. Try this
keys = [:foo, :bar]
vals = [1, 2]
Hash[*keys.zip(vals).flatten]
=> {:foo=>1, :bar=>2}
Solution 3
The following code will monkey patch Array and provide a to_h
method using the code give in @engineersmnky's comment, if to_h
isn't already defined - that is, in pre-2.1 ruby environments.
unless [].respond_to? :to_h
class Array
def to_h
Hash[self]
end
end
end
Solution 4
Ruby 2.0 doesn't support to_h method. its available in 2.1 and higher
Wand Maker
Wizard who helps muggles with programming issues I have made a small contribution to Ruby Language in the form of a bug fix which I solved as part of answering StackOverflow question.
Updated on June 06, 2022Comments
-
Wand Maker about 2 years
As per Ruby Array documentation, there is a method
to_h
which can be used to convert arrays to hash as long as each element of the array is another array of two elements. Example below from the same documentationp [[:foo, :bar], [1, 2]].to_h
However, when I run the above code, I get this error:
irb(main):001:0> p [[:foo, :bar], [1, 2]].to_h NoMethodError: undefined method `to_h' for [[:foo, :bar], [1, 2]]:Array from (irb):1 from E:/RubyInstall/bin/irb:12:in `<main>' irb(main):002:0>
My Ruby version is
C:\>ruby -v ruby 2.0.0p247 (2013-06-27) [x64-mingw32]
I wanted to use this technique to answer another question on Stackoverflow, but I am stuck now as a documented feature of Ruby is not working for me.
-
Wand Maker almost 9 yearsThanks. Will upgrade my Ruby. :-)
-
ReggieB over 7 yearsWorth noting that in the Ruby 2.1.0
to_h
documentation,[[:foo, :bar], [1, 2]].to_h
should result in{:foo => :bar, 1 => 2}
ruby-doc.org/core-2.1.0/Array.html#method-i-to_h