Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails mapping array of hashes onto single hash

I have an array of hashes like so:

 [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]

And I'm trying to map this onto single hash like this:

{"testPARAM2"=>"testVAL2", "testPARAM1"=>"testVAL1"}

I have achieved it using

  par={}
  mitem["params"].each { |h| h.each {|k,v| par[k]=v} } 

But I was wondering if it's possible to do this in a more idiomatic way (preferably without using a local variable).

How can I do this?

like image 438
Bart Platak Avatar asked Aug 08 '12 01:08

Bart Platak


People also ask

How do you merge an array of hashes in Ruby?

Method 2: Use the inject method Hash#merge creates a new hash on each iteration. For bigger arrays, it is more performant to use Hash#merge! / Hash#update .

How do I map an array in Ruby?

The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.

What is the difference between hashes and arrays?

In arrays, you have to loop over all items before you find what you are looking for while in a hash table you go directly to the location of the item. Inserting an item is also faster in Hash tables since you just hash the key and insert it.

How do you create a hash map in Ruby?

Creating a Hash In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.


2 Answers

You could compose Enumerable#reduce and Hash#merge to accomplish what you want.

input = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
input.reduce({}, :merge)
  is {"testPARAM2"=>"testVAL2", "testPARAM1"=>"testVAL1"}

Reducing an array sort of like sticking a method call between each element of it.

For example [1, 2, 3].reduce(0, :+) is like saying 0 + 1 + 2 + 3 and gives 6.

In our case we do something similar, but with the merge function, which merges two hashes.

[{:a => 1}, {:b => 2}, {:c => 3}].reduce({}, :merge)
  is {}.merge({:a => 1}.merge({:b => 2}.merge({:c => 3})))
  is {:a => 1, :b => 2, :c => 3}
like image 146
cjhveal Avatar answered Oct 18 '22 23:10

cjhveal


How about:

h = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
r = h.inject(:merge)
like image 55
shigeya Avatar answered Oct 18 '22 22:10

shigeya