Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Addition for hashes in Ruby

Why, oh, why is there no addition for hashes in Ruby? 'update' can do the trick, but only returns what was updated, rather than the whole updated hash. It also forces an update rather than being passive.

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)
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS