ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> ruby-talk
ruby-talk
Re: How to re-replace Hash default value behaviour?
by Matt Neuburg other posts by this author
May 8 2008 7:25PM messages near this date
Re: How to re-replace Hash default value behaviour? | Principle of le,err i mean biggest surprise!!??
Siep Korteling <s.korteling@[...].com>  wrote:

>  Hash.new(0) and the block form of Hash.new{_smart_stuff_}  come in
>  really handy while reading in a hash.
>  When the reading is done however, my hash serves to provide data. At
>  that stage, the default_value behaviour gets in the way. For instance,
>  if the hash contains the number of goals for soccerplayers, I don't want
>  the hash to return value "0" for the key "Wolfgang Amadeus Mozart"; by
>  then I want plain old Nil, or "No data available".
>  
>  failed experiment:
>  
>  Class Hash
>    def default_proc
>      Nil
>    end
>  end
>  
>  How can Hash.new behaviour be changed?
>  
>  regards,
>  Siep

h = Hash.new.merge(h)

So for example:

h = Hash.new(0)
h[:a] += 2
h[:a] += 1
h[:b] += 4
p h #=>  {:a=>3, :b=>4}

h = Hash.new.merge(h)
p h[:c] #=>  nil, it's now returning plain old nil

m.
-- 
matt neuburg, phd = matt@[...].com, http://www.tidbits.com/matt/
Leopard - http://www.takecontrolbooks.com/leopard-customizing.html
AppleScript - http://www.amazon.com/gp/product/0596102119
Read TidBITS! It's free and smart. http://www.tidbits.com
Thread:
Siep Korteling
Andrea Fazzi
Craig Demyanovich
Siep Korteling
Matt Neuburg

Privacy Policy | Email Opt-out | Feedback | Syndication
© 2004 ActiveState, a division of Sophos All rights reserved