<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: overriding code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 01:47:21 GMT</pubDate>
    <description>DZone Snippets: overriding code</description>
    <item>
      <title>Addition for hashes in Ruby</title>
      <link>http://snippets.dzone.com/posts/show/1535</link>
      <description>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.&lt;br /&gt;&lt;br /&gt;Sometimes you only want to temporarily do an add, and this is how I pulled it off:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;class Hash&lt;br /&gt;  def +(add)&lt;br /&gt;    temp = {}&lt;br /&gt;    add.each{|k,v| temp[k] = v}&lt;br /&gt;    self.each{|k,v| temp[k] = v}&lt;br /&gt;    temp&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Now you can do stuff like:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;x = { :a =&gt; 1 }&lt;br /&gt;y = { :b =&gt; 2 }&lt;br /&gt;&lt;br /&gt;# x + y =&gt; { :a =&gt; 1, :b =&gt; 2 }, but x and y are untouched&lt;br /&gt;# x + { :c =&gt; 3 } =&gt; { :a =&gt; 1, :c =&gt; 3 }&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;If you want to force an add, it's easy:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;x += y =&gt; { :a =&gt; 1, :b =&gt; 2 } (this is now what x contains)&lt;/code&gt;</description>
      <pubDate>Mon, 20 Feb 2006 08:48:52 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1535</guid>
      <author>peter (Peter Cooperx)</author>
    </item>
  </channel>
</rss>
