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

Addition for hashes in Ruby (See related posts)

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:

class Hash
  def +(add)
    temp = {}
    add.each{|k,v| temp[k] = v}
    self.each{|k,v| temp[k] = v}
    temp
  end
end


Now you can do stuff like:

x = { :a => 1 }
y = { :b => 2 }

# x + y => { :a => 1, :b => 2 }, but x and y are untouched
# x + { :c => 3 } => { :a => 1, :c => 3 }


If you want to force an add, it's easy:

x += y => { :a => 1, :b => 2 } (this is now what x contains)

Comments on this post

Qerub posts on Feb 20, 2006 at 17:32
You seem to have missed the
merge
method. Try this instead:

class Hash
def +(other)
merge(other)
end
end
peter posts on Feb 21, 2006 at 14:16
Aha, thanks! That's the last time I refer to the 1.6 docs rather than the 1.8! :)

That said, + is much nicer than 'merge', it seems a little odd they didn't go that way too. Thanks again!
willcodeforfoo posts on Apr 19, 2006 at 16:29
What about a true merge?


a = { :a => 1 }
b = { :a => 1, :b => 1 }
c = a + b
# I would want c = { :a => 2, :b => 1 }


Any ideas?
willcodeforfoo posts on Apr 19, 2006 at 16:37

class Hash
def +(add)
temp = {}
add.each { |k, v| temp[k] = v }
self.each { |k, v| temp[k] = v + add[k] unless add[k].nil? }
temp
end
end


That does it... not sure that there isn't a more efficient way, though.
willcodeforfoo posts on May 04, 2006 at 15:24
Turns out you can assign a block to merge...

So,

a = { :a => 1 }
b = { :a => 1, :b => 1 }
c = a.merge(b) { |key, old_value, new_value| old_value + new_value }
# c = { :a => 2, :b => 1 }


Results in a true merge, with addition

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts