How to make object instance a hash key in Ruby?

后端 未结 2 820
挽巷
挽巷 2021-02-01 14:54

I have a class Foo with a few member variables. When all values in two instances of the class are equal I want the objects to be \'equal\'. I\'d then like these objects to be

2条回答
  •  面向向阳花
    2021-02-01 15:17

    See http://ruby-doc.org/core/classes/Hash.html

    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.

    The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash as Marc-Andre suggests in the comments.

提交回复
热议问题