The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

How to Convert a Ruby Array into Hash Keys

TODO: Pull subtitle into page object

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_start_default_section code_end_default_section

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

How to Convert a Ruby Array into Hash Keys

-- p

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/
-- ruby

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

-- /code

-- p

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

-- code/
-- ruby

#!/usr/bin/env ruby

require 'pp'

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

pp array
pp hash

-- /code

-- p

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

-- code/
-- ruby

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

-- /code

-- p

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

-- code/
-- ruby

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

-- /code

-- p

would produce the hash with:

-- code/
-- ruby

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

-- /code


-- categories
-- Ruby

-- metadata
-- date: 2015-12-02 00:00:00
-- id: 20en65hw
-- status: published
-- type: post
-- SCRUBBED_NEO: false
-- site: aws