Javaでは次のことができます。
public boolean equals(Object other) {
return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}
これにより、クラスのカプセル化を壊すことなく、平等を定義できます。Rubyで同じことをするにはどうすればよいですか?
ありがとう。
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
他の人が指摘しているよう#==
に、クラスで再定義する必要があります。ただし、1つの落とし穴はハッシュテーブルです。クラスの2つの異なるインスタンスを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
Rubyでは不要なキャストなしで比較するだけです。
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?
されました==
。