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}

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


My solution isn’t that much more code, and handles the case of subarrays.


Ola makes the good point that this is actually the best of both worlds :


Thanks Ola. …I still think inject is cool, though :).


4 Responses to “Array.to_hash() in Ruby”

  1. Ola Bini Says:

    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

  2. kikito Says:

    Hi guys,

    How is this supposed to work? I don’t see Array.flatten accepting any arguments on the ruby apy.

  3. kikito Says:

    api*, sorry if your eyes hurt

  4. Devin Ben-Hur Says:

    kikito: It’s a feature of Ruby 1.9 Array#flatten.

    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 ().

Leave a Reply