What's the right way to implement equality in ruby

后端 未结 3 1291
攒了一身酷
攒了一身酷 2020-12-25 09:58

For a simple struct-like class:

class Tiger
  attr_accessor :name, :num_stripes
end

what is the correct way to implement equality correctly

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-25 10:41

    To test all your instance variables equality at once:

    def ==(other)
      other.class == self.class && other.state == self.state
    end
    
    def state
      self.instance_variables.map { |variable| self.instance_variable_get variable }
    end
    

提交回复
热议问题