The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hash.new gives me a rash

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Daniel Berger

Posts: 1383
Nickname: djberg96
Registered: Sep, 2004

Daniel Berger is a Ruby Programmer who also dabbles in C and Perl
Hash.new gives me a rash Posted: Jun 17, 2008 9:39 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Daniel Berger
Latest Posts From Testing 1,2,3...

Advertisement
Am I the only one who still, after several years, cannot remember the semantics of Hash.new? I recently did this:
hash = Hash.new(Hash.new(0))

When I really meant to do this:
hash = Hash.new{ |hash, key| hash[key] = Hash.new(0).dup }

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.

Read: Hash.new gives me a rash

Topic: Immaturity of Developer Testing Previous Topic   Next Topic Topic: Why you should upgrade to Rails 2.1

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use