题
在爪哇我可以这样做:
public boolean equals(Object other) {
return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}
这让我定义平等没有打破我的类的封装。 我怎么可以这样做在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
其他提示
正如其他人所指出的那样,你需要在你的类重新定义#==
。有一个问题,虽然是哈希表。如果你想与你的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?
到==
不隶属于 StackOverflow