在 Ruby 中访问同一个类的其他对象的成员变量

sou*_*ein 4 ruby java equals

在 Java 中,我可以这样做:

public boolean equals(Object other) {
    return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}
Run Code Online (Sandbox Code Playgroud)

这使我可以在不破坏类的封装的情况下定义相等性。我如何在 Ruby 中做同样的事情?

谢谢。

sep*_*p2k 6

在 ruby​​ 中,实例变量和私有方法只能被对象本身访问,而不能被任何其他对象访问,无论它们的类是什么。受保护的方法可用于对象本身和同一类的其他对象。

所以要做你想做的,你可以为你的变量定义一个受保护的 getter 方法。

编辑:一个例子:

class Foo
  protected
  attr_accessor :my_variable # Allows other objects of same class
                             # to get and set the variable. If you
                             # only want to allow getting, change
                             # "accessor" to "reader"

  public
  def ==(other)
    self.my_variable == other.my_variable
  end
end
Run Code Online (Sandbox Code Playgroud)