Donato Donato - 1 month ago 7
Ruby Question

Splitting a hash variable with reduce

When invoking

reduce
on an array of hashes, I thought I could split the hash by key and value within the parameters using the () technique. But in this case, it does not appear to work:

columns = [
{"lead"=>["source", 2]},
{"parent"=>["name", 4]}
]

columns.reduce({}) do |acc, (k,v)|
puts "k #{k} v #{v}"
end

# k {"lead"=>["source", 2]} v
# k {"parent"=>["name", 4]} v
# => nil


I expected
k
to be
"lead"
and
v
to be
["source", 2]
. Because columns is an array and not a hash, I cannot do this
(k,v)
to get the key/value pair of hash. Is there another technique I can use in argument list in order to pass the k/v pair rather than having to dissect it in the block?

Answer

It happens because the logic behind this parenthesis is basically a parallel assignment, which doesn't work in your case because each item in the collection is a hash. So practically what you can do it convert each item to array instead:

columns = columns.flat_map(&:to_a)

Demonstration