Apply an arithmetic operation using 2 hashes
1 users_hash = {"tom" => 1, 2 "adi" => 1, 3 "adi2" => 1, 4 "aaron" => 1 } 5 6 users_hash2 = {"tom" => 2, 7 "adi" => 3, 8 "aaron" => 4 } 9 10 class Hash 11 def +(hash2) 12 self.each do |key, value| 13 self[key] += hash2[key] if hash2.has_key? key 14 end 15 end 16 end 17 18 c = users_hash + users_hash2
=> {"adi2"=>1, "adi"=>4, "tom"=>3, "aaron"=>5}
update: 14:35 5-Sep-08
In addition, the following code copies over items from the right hash which are not present in the left hash:
1 class Hash 2 def +(hash2) 3 temp = Hash.new 4 self.each do |key, value| 5 temp[key] = self[key] + hash2[key] unless hash2[key].nil? 6 end 7 8 hash2.update(temp) 9 self.update(hash2) 10 end 11 end 12 13 c = users_hash + users_hash2
==> {"adi2"=>1, "adi3"=>3, "adi"=>1, "tom"=>3, "aaron"=>5}
Reference:
- Ruby hash merge (Add element to Ruby hash) - by Ruby on Rails [rubyonrailsexamples.com]
- Manipulating Structured Data in Ruby > Working with Hashes [informit.com]