Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

How to Convert a Ruby Array into Hash Keys

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 [TODO: Code shorthand span ] 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"}