Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging ruby hash with array of values into another hash with array of values

Tags:

ruby

hash

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!

like image 222
bfcoder Avatar asked Jun 23 '12 18:06

bfcoder


People also ask

How do you combine hashes in Ruby?

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.

How do you push values into an Array of hash in Ruby?

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.

Can a hash have multiple values 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.

How do you turn an Array into a hash in Ruby?

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.


1 Answers

{ "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 .

like image 149
megas Avatar answered Oct 22 '22 11:10

megas