I have two hash arrays:
a = [ { key: 1, value: "foo" }, { key: 2, value: "baz" } ] b = [ { key: 1, value: "bar" }, { key: 1000, value: "something" } ]
I want to combine them into one hash array, so essentially a + b , except that I want the duplicate key in b overwrite those in a . In this case, both a and b contain key 1 , and I want the final result to have a pair of b values.
Here's the expected result:
expected = [ { key: 1, value: "bar" }, { key: 2, value: "baz" }, { key: 1000, value: "something" } ]
I got it to work, but I was wondering if there is a less bland way to do this:
hash_result = {} a.each do |item| hash_result[item[:key]] = item[:value] end b.each do |item| hash_result[item[:key]] = item[:value] end result = [] hash_result.each do |k,v| result << {:key => k, :value => v} end puts result puts expected == result
source share