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] } )


Karthik Blog said...

hi how to check this with database when user enters

password it encryptes and when user enters it needs to check in database how is that possible

Dallas said...

or even more simply put:

x = [[:one, 1], [:two, 2], [:three, 3], [:four, 4]]
#=> [[:one, 1], [:two, 2], [:three, 3], [:four, 4]]
x.inject({}) {|h,(k,v)| h.merge(k => v)}
#=> {:two=>2, :one=>1, :three=>3, :four=>4}