h = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }
散列#合并适用于2个散列:h.merge(h2)
如何合并3个哈希?
h.merge(h2).merge(h3)
行,但有更好的方法吗?
h = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }
散列#合并适用于2个散列:h.merge(h2)
如何合并3个哈希?
h.merge(h2).merge(h3)
行,但有更好的方法吗?
你可以这样做:
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}
编辑:如果你有很多散列,这可能是正确的方法:
a.inject{|tot, new| tot.merge(new)}
# or just
a.inject(&:merge)