Which equality test does Ruby's Hash use when comparing keys?

前端 未结 2 2037
旧时难觅i
旧时难觅i 2020-12-18 04:56

I have a wrapper class around some objects that I want to use as keys in a Hash. The wrapped and unwrapper objects should map to the same key.

A simple example will

相关标签:
2条回答
  • 2020-12-18 05:20

    Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.

    So...

    class A
      attr_reader :x
      def initialize(inner)
        @inner=inner
      end
      def x; @inner.x; end
      def ==(other)
        @inner.x==other.x
      end
    
      def eql?(other)
        self == other
      end
    
      def hash
        x.hash
      end
    end
    
    0 讨论(0)
  • 2020-12-18 05:20

    You must define eql? and hash.

    The documentation of Hash was lacking but has been improved recently.

    0 讨论(0)
提交回复
热议问题