Addition for hashes in Ruby
Sometimes you only want to temporarily do an add, and this is how I pulled it off:
1 class Hash 2 def +(add) 3 temp = {} 4 add.each{|k,v| temp[k] = v} 5 self.each{|k,v| temp[k] = v} 6 temp 7 end 8 end
Now you can do stuff like:
1 x = { :a => 1 } 2 y = { :b => 2 } 3 4 # x + y => { :a => 1, :b => 2 }, but x and y are untouched 5 # x + { :c => 3 } => { :a => 1, :c => 3 }
If you want to force an add, it's easy:
1 x += y => { :a => 1, :b => 2 } (this is now what x contains)