Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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 `.collect` method like so:

Code

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

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

Code

#!/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:

Code

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

Code

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

would produce the hash with:

Code

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