From: "Peña, Botp" Date: 2007-07-04T16:28:44+09:00 Subject: Re: Isn't hash default value behavior just a little bizarre??? On Behalf Of Farhad Farzaneh: # Hash's default value object, not a copy of it. So if you modify that, # it modifies the default value, which then effects the default # value for every other new key. it is defined. irb(main):014:0> system "qri hash#new" -------------------------------------------------------------- Hash::new Hash.new => hash Hash.new(obj) => aHash Hash.new {|hash, 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 obj 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"] => true # I don't know, I wouldn't call this the "principle of least # surprise"... I was plenty surprised! ruby allows one to change the default value. that is good, imho. i think the surprise stems fr the fact that it is _too simple to change the default. hey, it's ruby ;) kind regards -botp