Hugh Sasse Staff Elec Eng <hgs / dmu.ac.uk> writes:

> The Ruby philosophy is that there is a better way to do things.  I
> expected Hash.new(thing) to give me a new thing for each undefined
> key of the Hash.  So my question is: "Why is it better to have a
> single default object shared, than to create a copy of the defualt
> object when an undefined key is referenced?"

I started out this note writing a long defense of the current way of
doing it, but in the middle of it, I managed to confused myself
sufficiently that I stopped and started again.

I seems to me that we could actually do it Perl's way (but better ;-)
with not too much each effort.

First, assignment to hash entries doesn't change at all. There's no
need: when you do a straight assignment, whatever's in that element
(default value or not) gets overwritten.

The issue actually comes on hash reference. This occurs whenever a
hash value is used in an expression.

     f = hash[key]
     print(hash[key])
     hash[key][0] = 123


In these circumstances, Hugh would like a new default value to be
created. So, Matz, how about the following:

1. Hash.new takes a second parameter:

    Hash.new(default,  genNewDefaults=false)

2. Whenever you currently return hash->ifnone, instead have

      default = hash->ifnone

      return default unless genNewDefaults

      if default.kind_of? Class
           return default.new
      else
           return default.dup
      end


This seems like it would be a useful thing to have that wouldn't break 
the existing semantics. If you wanted to consider this, I could hack
up a patch for 1.7.


Regards


Dave