How to Convert a Ruby Array into Hash Keys

December - 2015

A current project requires converting an array into a hash. The requirement is simple. The values of the array need to become the keys of the hash. Each key pointing to an empty value until more work is done later in the process. The approach I'm using is to the Ruby Array object's .collect method like so:

hash = Hash[array.collect { |item| [item, ""] } ]

It works great. Here's a demo script showing it in action:

#!/usr/bin/env ruby

require 'pp'

array = %w(cat hat bat mat)
hash = Hash[array.collect { |item| [item, ""] } ]

pp array
pp hash

The output of which confirms the hash is created exactly as I need:

["cat", "hat", "bat", "mat"]
{"cat"=>"", "hat"=>"", "bat"=>"", "mat"=>""}

Of course, the processing block can assign values as well. For example, changing the above example to use:

hash = Hash[array.collect { |item| [item, item.upcase] } ]

would produce the hash with:

{"cat"=>"CAT", "hat"=>"HAT", "bat"=>"BAT", "mat"=>"MAT"}