Acceso a variables miembro de otro objeto de la misma clase en Ruby
Pregunta
En Java puedo hacer:
public boolean equals(Object other) {
return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}
Esto me permite definir la igualdad sin romper la encapsulación de mi clase. ¿Cómo puedo hacer lo mismo en Ruby?
Gracias.
Solución
En Ruby, las variables y los métodos privados solo son accesibles para el objeto en sí, no para cualquier otro objeto, sin importar su clase. Los métodos protegidos están disponibles para el objeto en sí y para otros objetos de la misma clase.
Entonces, para hacer lo que quiera, puede definir un método getter protegido para su variable.
Editar: Un ejemplo:
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
Otros consejos
Como otros han señalado, debe redefinir # ==
en su clase. Sin embargo, un problema es las tablas hash. Si desea dos instancias diferentes de su clase con o1 == o2 # = > true
para hacer hash con el mismo valor en una tabla hash, luego debe redefinir #hash
y #eql?
para que la tabla hash sepa que representan lo mismo valor.
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
Simplemente haga la comparación sin el elenco que no es necesario en 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
Editar : ¿Se cambió igual?
a ==
.