比较ruby中的对象 [英] Comparing objects in ruby
本文介绍了比较ruby中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑:
class Aaa
attr_accessor :a, :b
end
x = Aaa.new
x.a, x.b = 1,2
y = Aaa.new
y.a, y.b = 1,2
puts x == y #=>false
是否有某种方法检查所有公共属性在类中是否相等相同类型?
Is there some way to check if all public attributes are equal in classes of same type?
推荐答案
class Aaa
attr_accessor :a, :b
def ==(other)
return self.a == other.a && self.b == other.b
end
end
x = Aaa.new
x.a,x.b = 1,2
y = Aaa.new
y.a,y.b = 1,2
y = Aaa.new
y.a,y.b = 1,2
z = Aaa.new
z.a,z.b = 1,3
x == y # => true
x == z # => false
这篇关于比较ruby中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文