Rubyで同じクラスの他のオブジェクトのメンバー変数にアクセスする
質問
Javaでできること:
public boolean equals(Object other) {
return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}
これにより、クラスのカプセル化を壊さずに平等を定義できます。 Rubyでも同じことができますか?
ありがとう。
解決
Rubyインスタンス変数とプライベートメソッドは、オブジェクト自体にのみアクセスでき、クラスに関係なく他のオブジェクトにはアクセスできません。保護されたメソッドは、オブジェクト自体と同じクラスの他のオブジェクトで使用できます。
したがって、必要なことを行うには、変数の保護されたゲッターメソッドを定義できます。
編集:例:
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つの落とし穴はハッシュテーブルです。 o1 == o2#=>を使用してクラスの2つの異なるインスタンスが必要な場合ハッシュテーブル内の同じ値にハッシュするには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?
を ==
に変更しました。
所属していません StackOverflow