【发布时间】:2009-12-02 03:22:07
【问题描述】:
如果我有两个数组a 和b,那么包含的对象应该重写什么方法,这样减法- 才能正常工作?
eql?够了吗
编辑
我正在为我的问题添加更多细节。
我已经定义了这个类:
class Instance
attr_reader :id, :desc
def initialize( id , desc )
@id = id.strip
@desc = desc.strip
end
def sameId?( other )
@id == other.id
end
def eql?( other )
sameId?( other ) and @desc == other.desc
end
def to_s()
"#{id}:#{desc}"
end
end
好吗?
然后我从不同的部分填充了我的两个数组,我想得到不同。
a = Instance.new("1","asdasdad")
b = Instance.new("1","a")
c = Instance.new("1","a")
p a.eql?(b) #false
p b.eql?(c) #true
x = [a,b]
y = [c]
z = x - y # should leave a because b and c "represent" the same object
但这不起作用,因为a 和b 被保存在数组中。我想知道我需要在我的类中重写什么方法才能使其正常工作。
【问题讨论】:
-
你能定义“正常工作”吗?现在,从array1 中减去array2 将删除array1 中存在于array2 中的任何项目。我想这似乎是想要的效果。
-
@dcneiner:每个对象? ...我正在定义...让我把它放在问题上
标签: ruby arrays subtraction