Joel VanderWerf
10/30/2007 10:07:00 PM
ara.t.howard wrote:
>
> On Oct 30, 2007, at 3:40 PM, Joel VanderWerf wrote:
>
>> This works...
>>
>> count = Hash.new{|h,k| h[k] = Hash.new{|h1,k1| h1[k1] = 0}}
>> => {}
>> count[:foo][1] += 1
>> => 1
>> count[:foo][1] += 1
>> => 2
>> count[:foo][1] += 1
>> => 3
>
> oh yeah, of course ;-) i'm in the habbit of using 'update' from
> 'inject' where is saves you having to return the hash itself... shorter
> is better always.
...but only if returning the hash is the right thing to do. In this
case, we want the "leaf" value, not the hash:
irb(main):034:0> count = Hash.new{|h,k| h.update k => Hash.new{|hh,kk|
hh.update kk => 0}}
=> {}
irb(main):035:0> count[:foo][1] += 1
NoMethodError: undefined method `+' for {1=>{}, :foo=>{}}:Hash
from (irb):35
irb(main):036:0> count
=> {1=>{}, :foo=>{}}
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407