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?
You could compose
Enumerable#reduce
andHash#merge
to accomplish what you want.Reducing an array sort of like sticking a method call between each element of it.
For example
[1, 2, 3].reduce(0, :+)
is like saying0 + 1 + 2 + 3
and gives6
.In our case we do something similar, but with the merge function, which merges two hashes.
How about:
Use #inject