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.

Convert a Ruby Array into the Keys of a New Hash

The need to migrate an array into a hash crops up on occasion. The simplest approach is to turn each array item into a hash key pointing at an empty value. A situation where the Ruby Array object's [TODO: Code shorthand span ] method works great. For example :

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

Fleshing it out a bit more, here's a full demo 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

which produces the output showing the original array and then the hash with the desired structure :

["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"}

Good stuff.

P.S. Let me know if you have a simpler way to turn [TODO: Code shorthand span ] into ` {"cat"= > "", "hat"= > "", "bat"= > "", "mat"= > ""} ` .