Hello --

On Sat, 6 Jan 2001, Mathieu Bouchard wrote:

> > for the compatibility, the default Hash#key_missing should be
> > class Hash
> >   def key_missing(key)
> >     nil
> >   end
> > end
> > And my question is what functionality am I missing compare to
> > Hash@default and its accessors? (other than compatibility)
> 
> well, if instead it's
> 
> class Hash
>   def key_missing(key)
>     default
>   end
> end
> 
> then I don't think you're missing any functionality. Except that #[] (and
> such) call the internal Hash#default directly, so trying to
> overload/redefine it does not work. 

You can get around that, I think, with #has_key?

  class Hash
    alias :oldget :[]
    def [](k)
      if has_key? k
	oldget(k)
      else
	# whatever default action you want to take
      end
    end
  end

(See [ruby-talk:8720] for some hacking along these lines.)  #has_key?
and #[] both branch on the same direct hash-table lookup of the key,
so by sticking #has_key? in the middle of #[], you're really just
doing what the original #[] does.

I'd be interested in exploring further what can/cannot be done with this.


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav