53

对于一个简单的类结构类:

class Tiger
  attr_accessor :name, :num_stripes
end

什么是正确实现相等的正确方法,以确保 、=====eql?工作,并让类的实例在集合、散列等中很好地发挥作用。

编辑

另外,当您想基于未在类外公开的状态进行比较时,有什么好的方法来实现平等?例如:

class Lady
  attr_accessor :name

  def initialize(age)
    @age = age
  end
end

在这里,我希望我的平等方法将@age 考虑在内,但女士不会将她的年龄暴露给客户。在这种情况下我必须使用 instance_variable_get 吗?

4

3 回答 3

75

要简化具有多个状态变量的对象的比较运算符,请创建一个将对象的所有状态作为数组返回的方法。然后只是比较两种状态:

class Thing

  def initialize(a, b, c)
    @a = a
    @b = b
    @c = c
  end

  def ==(o)
    o.class == self.class && o.state == state
  end

  protected

  def state
    [@a, @b, @c]
  end

end

p Thing.new(1, 2, 3) == Thing.new(1, 2, 3)    # => true
p Thing.new(1, 2, 3) == Thing.new(1, 2, 4)    # => false

此外,如果您希望类的实例可用作哈希键,请添加:

  alias_method :eql?, :==

  def hash
    state.hash
  end

这些需要公开。

于 2009-12-26T19:33:07.487 回答
23

一次测试所有实例变量的相等性:

def ==(other)
  other.class == self.class && other.state == self.state
end

def state
  self.instance_variables.map { |variable| self.instance_variable_get variable }
end
于 2014-09-01T13:10:16.013 回答
1

通常与==运营商。

def == (other)
  if other.class == self.class
    @name == other.name && @num_stripes == other.num_stripes
  else
    false
  end
end
于 2009-12-19T01:25:09.403 回答