I can't seem to find anywhere that talks about doing this.
Say I have a hash {"23"=>[0,3]}
and I want to merge in this hash {"23"=>[2,3]}
to result with this hash {"23"=>[0,2,3]}
Or how about {"23"=>[3]}
merged with {"23"=>0}
to get {"23"=>[0,3]}
Thanks!
We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.
Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.
Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.
{ "23" => [0,3] }.merge({ "23" => [2,3] }) do |key, oldval, newval|
oldval | newval
end
#=> {"23"=>[0, 3, 2]}
More generic way to handle non-array values:
{ "23" => [0,3] }.merge({ "23" => [2,3] }) do |key, oldval, newval|
(newval.is_a?(Array) ? (oldval + newval) : (oldval << newval)).uniq
end
Updated with a Marc-André Lafortune's hint .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With