From: "Peña, Botp" Date: 2007-09-03T17:36:23+09:00 Subject: Re: assigning to hash keys when there is a default value? From: 7stud -- [mailto:dolgun@excite.com] # I don't think it's a bug; dBlack was referring to this: irb(main):001:0> h = Hash.new 5 => {} irb(main):002:0> h[2] => 5 irb(main):003:0> h => {} irb(main):004:0> h[2] = h[2] => 5 irb(main):005:0> h => {2=>5} irb(main):006:0> 5 || 10 => 5 irb(main):007:0> h[3] = 5 || 10 => 5 irb(main):008:0> h => {2=>5, 3=>5} irb(main):009:0> h[4] = h[4] || 10 => 5 irb(main):010:0> h => {2=>5, 3=>5, 4=>5} irb(main):011:0> h[5] ||= 10 => 5 after that step above, you must have h[5] or 5=>5 irb(main):012:0> h => {2=>5, 3=>5, 4=>5} sadly none :( however, the ff works (wc is supposed to be the longcut version for h[5] ||= 10) irb(main):013:0> h[5] = h[5] || 10 => 5 irb(main):014:0> h => {5=>5, 2=>5, 3=>5, 4=>5} # the two examples are set forth on p. 276 of # "The Ruby Way (2nd ed)". However, no explanation is given # for why the two examples work differently. they should be different (note, that has nothing to do w the bug dBlack is pointing at) and the output should be, 5 {2=>5} #<---dblack is complaining here because the ruby output is {} nil {2=>10} pls refer to the hash#new document. irb(main):015: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"] kind regards -botp