Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple hashes in Ruby?

Tags:

ruby

hash

h  = { a: 1 } h2 = { b: 2 } h3 = { c: 3 } 

Hash#merge works for 2 hashes: h.merge(h2)

How to merge 3 hashes?

h.merge(h2).merge(h3) works but is there a better way?

like image 584
B Seven Avatar asked Oct 23 '13 17:10

B Seven


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.

What is Array of hashes in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.

How do you know if two hashes are equal Ruby?

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared.


2 Answers

Since Ruby 2.0 on that can be accomplished more graciously:

h.merge **h1, **h2 

And in case of overlapping keys - the latter ones, of course, take precedence:

h  = {} h1 = { a: 1, b: 2 } h2 = { a: 0, c: 3 }  h.merge **h1, **h2 # => {:a=>0, :b=>2, :c=>3}  h.merge **h2, **h1 # => {:a=>1, :c=>3, :b=>2} 
like image 44
Oleg Afanasyev Avatar answered Oct 03 '22 11:10

Oleg Afanasyev


You could do it like this:

h, h2, h3  = { a: 1 }, { b: 2 }, { c: 3 } a  = [h, h2, h3]  p Hash[*a.map(&:to_a).flatten] #= > {:a=>1, :b=>2, :c=>3} 

Edit: This is probably the correct way to do it if you have many hashes:

a.inject{|tot, new| tot.merge(new)} # or just a.inject(&:merge) 
like image 156
hirolau Avatar answered Oct 03 '22 12:10

hirolau