Marcin Mielzynski
6/10/2006 10:35:00 AM
billmcn wrote:
> I created a simple class that subclasses the Hash item assignment. The
> super function does differernt things depending on whether I use the
> store or []= function. For example, this code works
>
> class GoodHashSubclass < Hash
> def store(item, value)
> super.store(item, value)
> end
> end
>
> good = GoodHashSubclass.new
> good["dog"] = 5
> puts good.inspect
>
> It prints {"dog"=>5} as I would expect.
>
> This code--which differs only in that I use []= instead of store--does
> not work.
>
> class BadHashSubclass < Hash
> def []=(item, value)
> super.store(item, value)
> end
> end
>
> bad = BadHashSubclass.new
> bad["dog"] = 5
> puts bad.inspect
>
> The BadHashSubclass code generates the following error
>
> ./subhash.rb:11:in `[]=': undefined method `store' for 5:Fixnum
> (NoMethodError)
>
You will get the same error trying:
super.[]=(item, value)
The reason is that without parameters super calls superclass method with
the same name passing all parameters by default. Store and []= methods
(they are the same, see in hash.c) return value given as a parameter (in
your case 5)
lopex