This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Hash.new gives me a rash
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
For those following along, the first argument to Hash.new is the default value used for keys referenced on the fly. Anyway, the reason the first one doesn't work as expected is because it refers to the same hash reference, instead of creating a new one on the fly for each key.
I have yet to find this behavior useful in practice outside of simple types, e.g. Hash.new(0). On the contrary, it's definitely sucked away some of my productivity. Plus, the actual solution is ugly, and it has to be explained to newbies over, and over and over.
I guess the problem is that, for simple types, you don't want to dup the argument, otherwise you're wasting memory and cpu cycles.
I think for Sapphire I'm going to alter the interface to take an optional second argument so that you can do this:
hash1 = Hash.new(Hash.new(0), true) # Create dups
hash2 = Hash.new(0) # Do NOT create dups
The second argument (which I'll call :create_new_reference or something) explicitly states that, yes, I want a new reference for every default value instead of re-using the same reference. The default would be false.