Gyepi Sam
A Ruby Array to_hash Method

Ruby arrays do not have a to_hash method so if one wanted to convert the array

%w(one 1 two 2 three 3)

to a hash, there is no quick and simple solution. Granted, for this simple example, one could say:

hash = Hash[*array]

but it’s more elegant to extend the array class and add a to_hash method:

  class Array
    def to_hash
      self.each_slice(2).inject({}) { |hash, (key, value)| hash[key] = value; hash }

This method returns a new hash based on the array contents, which are assumed to be in key, value order.

If the array has an odd number of elements, the last entry will become a key with a nil value. So, if the array has an odd number of elements, it will essentially be extended with a nil during the each_slice operation and the nil value will appear as a hash value.

After this definition, one could say hash = array.to_hash and get the job done!