From: Jason Creighton Date: 2003-09-04T11:04:34+09:00 Subject: Re: show me the ruby way On 2 Sep 2003 14:21:46 -0700 aero6dof@yahoo.com (Alan Chen) wrote: > ts wrote in message news:<200309021525.h82FPkM17085@moulon.inra.fr>... > > try this (only with ruby-1.8) > > > > metaData = Hash.new {|h, k| h[k] = Hash.new(0) } > > > > when ruby try to access a key which is not defined, it call the block with > > (hash, key), you store in hash[key] a new hash with `0' as default value > > On a related note, with ruby 1.8.0 (2003-08-04) [i386-mswin32], > 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? ~$ ri Hash.new This is a test 'ri'. Please report errors and omissions on http://www.rubygarden.org/ruby?RIOnePointEight -------------------------------------------------------------- Hash::new Hash.new -> aHash Hash.new( anObject ) -> aHash Hash.new {| aHash, key | block } -> aHash ------------------------------------------------------------------------ Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn't correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If anObject is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required. h = Hash.new("Go Fish") h["a"] = 100 h["b"] = 200 h["a"] #=> 100 h["c"] #=> "Go Fish" # The following alters the single default object h["c"].upcase! #=> "GO FISH" h["d"] #=> "GO FISH" h.keys #=> ["a", "b"] # While this creates a new default object each time h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" } h["c"] #=> "Go Fish: c" h["c"].upcase! #=> "GO FISH: C" h["d"] #=> "Go Fish: d" h.keys #=> ["c", "d"] ~$ So yes, I think it is intentional. Jason Creighton