문제

자바에서는 할 수 있습니다.

public boolean equals(Object other) {
    return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}

이를 통해 수업의 캡슐화를 깨지 않고 평등을 정의 할 수 있습니다. 루비에서 어떻게 똑같이 할 수 있습니까?

감사.

도움이 되었습니까?

해결책

루비 인스턴스 변수와 개인 메소드는 클래스에 관계없이 다른 객체가 아니라 객체 자체에만 액세스 할 수 있습니다. 보호 된 방법은 객체 자체와 동일한 클래스의 다른 객체에 사용할 수 있습니다.

따라서 원하는 것을 수행하려면 변수에 대한 보호 된 getter-method를 정의 할 수 있습니다.

편집 : 예 :

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

다른 팁

다른 사람들이 지적했듯이, 당신은 재정의해야합니다 #== 당신의 수업에서. 그러나 Gotcha는 해시 테이블입니다. 수업의 두 가지 인스턴스를 원한다면 o1 == o2 #=> true 해시 테이블에서 동일한 값을 해시하려면 재정의해야합니다. #hash 그리고 #eql? 따라서 해시 테이블은 그들이 동일한 값을 나타내는 것을 알고 있습니다.

class Foo
  def initialize(x,y,z)
    @x,@y,@z = x,y,z
  end
  def ==(other)
    @y == other.instance_eval { @y }
  end
end

o1 = Foo.new(0, :frog, 2)
o2 = Foo.new(1, :frog, 3)

o1 == o2 #=> true

h1 = Hash.new
h1[o1] = :jump
h1[o2] #=> nil

class Foo
  def hash
    @y.hash
  end
  def eql?(other)
    self == other
  end
end

h2 = Hash.new
h2[o1] = :jump_again
h2[o2] #=> :jump_again

루비에서 필요하지 않은 캐스트없이 비교를하십시오.

class C1
  attr_accessor :property

  def == other
    property == other.property
  end
end

class C2
  attr_accessor :property

  def == other
    property == other.property
  end
end

c1 = C1.new
c1.property = :foo

c2 = C2.new
c2.property = :bar

p c1 == c2 # => false

c1.property = :bar
p c1 == c2 # => true

편집하다: 변경 equals? 에게 ==.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top