super behavior different in store and []= not in Hash subclass

B

billmcn

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 []= functions. 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)

For some reason super is finding the superclass of the value 5 rather
than the superclass of self. This looks wrong to me. Is this the
expected behavior?

Thanks.
--wpm
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top