Sunday, September 14, 2008

Using inject/reduce to create hashes in ruby

I have been using map and reduce/inject (reduce is the new name for inject in ruby) quite a bit lately and learning quite a bit in the process. Map was pretty easy, inject on the other hand has been giving me some trouble. Recently I have been playing around with using inject with hashes, what follows is some of what I learned.

Given the following structure:
old_structure = [['username', 'bob'], ['password','secret']]

Converting to the following more appropriate structure can be done several ways:
new_structure = {'username' => 'bob',  'password' => 'secret'}

Method 1: Without using inject

new_structure = {}
old_structure.each do |element|
hash[element[0]] = element[1]

Method 2: Using inject

new_structure = old_structure.inject({}) do |results, element|
results[element[0]] = element[1]

Method 3: Using inject with a little cleaner syntax

new_structure = old_structure.inject({}) do |results, element|
results.merge( { element[0] => element[1] } )