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.

Convert a Ruby Array into the Keys of a New Hash

TODO: Pull subtitle into page object

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 `.collect` method works great. For example:

code_start_default_section code_end_default_section

Good stuff.

P.S. Let me know if you have a simpler way to turn `["cat", "hat", "bat", "mat"]` into `{"cat"=<"", "hat"=<"", "bat"=<"", "mat"=<""}`.

Debugging Stuff

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

        -- title

Convert a Ruby Array into the Keys of a New Hash

-- p

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 `.collect` method works great. For example:

-- code/
-- ruby{numberLines: true}

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

-- /code

-- p

Fleshing it out a bit more, here's a full demo showing it in action:

-- code/
-- ruby{numberLines: true}

#!/usr/bin/env ruby

require 'pp'

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

pp array
pp hash

-- /code

-- p

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

-- code/
-- ruby{numberLines: true}

["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{numberLines: true}

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

-- /code

-- p

would produce the hash with:

-- code/
-- ruby{numberLines: true}

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

-- /code

-- p

Good stuff.

-- p

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


-- categories
-- Dev

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