在编写带有大量实例变量的大类时,编写 ==, eql? 和哈希方法是一个很大的麻烦。有没有办法制作一个“模板类”来自动化这个过程?或者用任何其他方式。
例子:
class Template
def ==(other)
//Some way of comparing all of self's instance variables to other's.
end
def eql?(other)
self == other
end
def hash
//Some way of XORing the instance variables of self
end
end
class Test < Example
attr_reader :foo
attr_reader :bar
def initialize(foo, bar)
@foo = foo
@bar = bar
end
end
a = Test.new "123", "456"
b = Test.new "123", "456"
a == b
> true