Array.to_hash() in Ruby
I often find myself wanting this method. This is my 3rd or 4th writing of it – it’s shorter this time. Inject is my new best friend.
class Array def to_hash inject({}) {|hash, i| hash[i[0]] = i[1]; hash} end end
What this snippet does is take an array and turn it into a hash, like so
[["apple", 1], ["banana", 2], ["citrus", [3,4,5]] => {"apple" => 1, "banana" => 2, "citrus" => [3,4,5]}
If I didn’t have to deal with the case where there may be subarrays, I’d use nick’s approach
Hash[*self.flatten]
My solution isn’t that much more code, and handles the case of subarrays.
Update
Ola makes the good point that this is actually the best of both worlds :
Hash[*self.flatten[1]]
Thanks Ola. …I still think inject is cool, though :).
Tags: ruby
August 4th, 2009 at 7:07 am
If you care about subarrays, why don’t you just give flatten an argument?
Hash[*self.flatten(1)] will give you what you want.nn1
October 6th, 2009 at 2:04 pm
Hi guys,
How is this supposed to work? I don’t see Array.flatten accepting any arguments on the ruby apy.
October 6th, 2009 at 2:05 pm
api*, sorry if your eyes hurt
October 28th, 2009 at 4:46 pm
kikito: It’s a feature of Ruby 1.9 Array#flatten.
http://ruby-doc.org/ruby-1.9/classes/Array.src/M000751.html
1.8.6 delivers ArgumentError. 1.8.7 appears to have backported it.
Jeremy: when you hoisted Ola’s suggestion into your update, you used [] when you meant ().