How to combine one hash with another hash in ruby

It’s a pretty straight-forward operation if you’re just interleaving:

c = a.merge(b)

If you want to actually add the values together, this would be a bit trickier, but not impossible:

c = a.dup
b.each do |k, v|
  c[k] ||= 0
  c[k] += v
end

The reason for a.dup is to avoid mangling the values in the a hash, but if you don’t care you could skip that part. The ||= is used to ensure it starts with a default of 0 as nil + 1 is not valid.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)