Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/19548496/how-to-merge-multiple-hashes-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
383 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...