Ruby Array to Hash



This tutorial expands on Ruby arrays and Ruby Hash and explains how do you convert array to hashmaps in Ruby.

There are couple of ways to convert arrays to hash as follows:

Ruby Array to Hash Method 1:

In this code we convert an array to its hash, by using 2 functions to_hashkeys or to_hashvalues as follows:

class Array
  def to_hashkeys(&block)
    Hash[*self.collect { |v|
      [v, block.call(v)]
    }.flatten]
  end
 
  def to_hashvalues(&block)
    Hash[*self.collect { |v|
      [block.call(v), v]
    }.flatten]
  end
end

This would work as follows:

>> a = ["a", "b", "c"]
>> a.to_hashvalues {|v| a.index(v)}
=> {0=>"a", 1=>"b", 2=>"c"}

Ruby Array to Hash Method 2

class Array
  def to_hash(other)
    Hash[ *(0...self.size()).inject([]) { |arr, ix| arr.push(self[ix], other[ix]) } ]
  end
end
%W{ a b c }.to_hash( %W{ 1 2 3 } )
 
#=> {"a"=>"1", "b"=>"2", "c"=>"3"}

The above ruby code is merging 2 arrays into hashmap.

%w(a b) is a shortcut for ["a", "b"]. This means it is another way of writing an array of strings seperated by spaces instead of commas and without quotes around them.

Simpler Ruby 1.9 Onwards Array to Hash Method

Ruby < 1.9 the array to hash would be:

a = [1, 2, 3].collect { |v| [v, v*2] }      # => [ [1, 2], [2, 4], [3, 6] ]
Hash[*a.flatten]                            # => {1=>2, 2=>4, 3=>6}

Ruby 1.9 Onwards, it is simpler:

a = [1, 2, 3].collect { |v| [v, v*2] }      # => [ [1, 2], [2, 4], [3, 6] ]
Hash[a]                                     # => {1=>2, 2=>4, 3=>6}

What if we want Hash to Array conversion?

h = { :a => 1, :b => 2}   # Start with a hash
a = h.to_a                # => [[:b,2], [:a,1]]: associative array
a.assoc(:a)               # => [:a,1]: subarray for key :a
a.assoc(:b).last          # => 2: value for key :b
a.rassoc(1)               # => [:a,1]: subarray for value 1
a.rassoc(2).first         # => :b: key for value 2
a.assoc(:c)               # => nil
a.transpose               # => [[:a, :b], [1, 2]]: swap rows and cols