需要什么方法才能有“-”? (减法) 方法与 Ruby 数组一起使用吗?
如果我有两个数组 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
被保存在数组中。我想知道我需要在类中重写什么方法才能正常工作。
If I have two arrays a
and b
, what method should the object contained have to override so the subtract method -
works properly?
Is it enough with eql?
EDIT
I'm adding more detail to my question.
I have this class defined:
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
Ok?
Then I have filled my two arrays from different parts and I want to get the difference.
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
But this is not working, because a
and b
are being kept in the array. I'm wondering what method to I need to override in my class for this to work properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要重新定义
#eql?
和 哈希< /a> 方法。您可以将其定义为:
详细信息:
查看 Ruby 1.9 中调用的内容:
ruby 1.8.7 中也是如此
You need to redefine
#eql?
and the hash method.You may define it as:
Details:
To see what's being called in Ruby 1.9:
The same is true in ruby 1.8.7