Ilya O.
Ilya O.

Reputation: 1500

Weird behavior when subclassing Hash

I'm trying to subclass Ruby's Hash to introduce my own behavior when a specific key is accessed. This requires an additional parameter when constructing, so I have implemented my custom hash like so:

class PlayerCollection < Hash
    def new(server)
        @server_player = SpecialPlayer.new(server, "Server")
        super(nil)
    end

    def [](key)
        key == "Server" ? @server_player : super(key)
    end

    def []=(key, value)
        key == "Server" ? value : super(key, value)
    end
end

As you can see, I'm calling super with a value of nil, as I'd like my hash to return nil when the value is not found in the hash. However, my hash ends up returning the server object when the key is not found, as though I've created my hash with Hash.new(server)!

How can I avoid this behavior? Any help would be appreciated!

Upvotes: 1

Views: 251

Answers (1)

undur_gongor
undur_gongor

Reputation: 15954

In your PlayerCollection, you should overwrite Hash#initialize rather than Hash#new.

That new is not called. It's the class method Hash.new (or PlayerCollection.new) which gets called.

Upvotes: 3

Related Questions