From: aero6dof@... (Alan Chen) Date: 2003-09-03T10:54:09+09:00 Subject: Re: show me the ruby way Hmm, I meant h[k] not h[h] as I originally posted below... md = Hash.new { |h,k| h[k] = 0; 3 } # access undefined key 1 p md[1] # => 3 # returns the block result p md[1] # => 0 # now we discover the actual default value It's clear to me exactly what is happening, but I guess my thought was that this behavior is a bug. If the code that runs the autovivication block can recognize that the value for the undefined key was set, then perhaps the block return value should be ignored. I guess it would require an additional st_lookup after the initial lookup fails. "Warren Brown" wrote in message news:<005101c3719d$c091ca50$670b88cf@warrenpc>... > alan, > > > I was wondering about this behavior: > > > > md = Hash.new { |h,k| h[h] = 0; 3 } > > p md[1] # => 3 > > p md[1] # => 0 > > > > I understand that the first "p md[1]" is returning > > the result of the block; is that intentional? > > Yes. A clearer example: > > md = Hash.new { 3 } > md[1] = 1 > p md[1] => 1 > p md[2] => 3 > p md => {1=>1} > > Remember, the main point of the block is to generate a default value for > nonexistent keys. The autovivication trick is merely an extension of this > functionality. > > I hope this helps. > > - Warren Brown