Skip directly to content

Array to Hash in Ruby

on Thu, 08/11/2011 - 19:18

To be able to converting hash into array in Ruby is easy but how do we convert an array into a hash? This tutorial did the ruby array to hash trick.

RUBY:
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"}

If you are looking to wonder what hash map is, check out this Ruby Hash.