How to make object instance a hash key in Ruby?

后端 未结 2 818
挽巷
挽巷 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:36

    Add a method called 'hash' to your class:

    class Foo
      def hash
        return whatever_munge_of_instance_variables_you_like
      end
    end
    

    This will work the way you requested and won't generate different hash keys for different, but identical, objects.

提交回复
热议问题