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]
end
Method 2: Using inject
new_structure = old_structure.inject({}) do |results, element|
results[element[0]] = element[1]
results
end
Method 3: Using inject with a little cleaner syntax
new_structure = old_structure.inject({}) do |results, element|
results.merge( { element[0] => element[1] } )
end
2 comments:
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
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}
Post a Comment