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 `.collect` method works great. For example:
Code
hash = Hash[array.collect { |item| [item, ""] } ]
Fleshing it out a bit more, here's a full demo 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
which produces the output showing the original array and then the hash with the desired structure:
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"}
Good stuff.
P.S. Let me know if you have a simpler way to turn `["cat", "hat", "bat", "mat"]` into `{"cat"=>"", "hat"=>"", "bat"=>"", "mat"=>""}`.