Hi --

On Thu, 10 Oct 2002, William Djaja Tjokroaminata wrote:

> Hi David,
>
> Probably the problem is not that bad.  A hash value can be populated with
> the default value only when the hash[key] is called as an rvalue.  As an
> (imaginary) example:
>
>     hsh = Hash.new ('a')
>     puts hsh['x']  # >> 'a'
>     puts hsh['y']  # >> 'a'
>     hsh.keys       # ->  ['x', 'y']

You can do that like this:

  class Hash
    alias :oldget :[]
    def [](k)
      v = oldget(k)
      self[k] = v unless has_key?(k)
      v
    end
  end

It's a bit too "magic" for my taste.  It fights against the notion of
a default, by only defaulting once.  So if you change the default
dynamically, hsh["x"] won't default to the new default:

  puts hsh["k"]       # "a"

# ...

  hsh.default = "b"
  puts hsh["k"]       # "a"


David

-- 
David Alan Black                      | Register for RubyConf 2002!
home: dblack / candle.superlink.net     | November 1-3
work: blackdav / shu.edu                | Seattle, WA, USA
Web:  http://pirate.shu.edu/~blackdav | http://www.rubyconf.com