Array#-(减法运算符)如何比较元素是否相等?
当我调用 Array#- 时,它似乎没有对我正在比较的字符串调用任何比较方法:
class String
def <=>(v)
puts "#{self} <=> #{v}"
super(v)
end
def ==(v)
puts "#{self} == #{v}"
super(v)
end
def =~(v)
puts "#{self} =~ #{v}"
super(v)
end
def ===(v)
puts "#{self} == #{v}"
super(v)
end
def eql?(v)
puts "#{self}.eql? #{v}"
super(v)
end
def equal?(v)
puts "#{self}.equal? #{v}"
super(v)
end
def hash()
puts "#{self}.hash"
super
end
end
p %w{one two three} - %w{two}
它只是返回:
["one", "three"]
那么,Array#- 正在做什么?
另外,我正在使用 Ruby 1.9.2p290。在 1.8.7 中它似乎会导致无限循环。
When I call Array#-
it doesn't seems to call any comparison method on the strings I'm comparing:
class String
def <=>(v)
puts "#{self} <=> #{v}"
super(v)
end
def ==(v)
puts "#{self} == #{v}"
super(v)
end
def =~(v)
puts "#{self} =~ #{v}"
super(v)
end
def ===(v)
puts "#{self} == #{v}"
super(v)
end
def eql?(v)
puts "#{self}.eql? #{v}"
super(v)
end
def equal?(v)
puts "#{self}.equal? #{v}"
super(v)
end
def hash()
puts "#{self}.hash"
super
end
end
p %w{one two three} - %w{two}
It just returns:
["one", "three"]
So, what is Array#-
doing?
Also, I'm using Ruby 1.9.2p290. In 1.8.7 it seems to cause an infinite loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Array#-
的源代码。看起来不是测试相等性,而是从第二个数组创建哈希。该数组中未包含的任何内容都会被推入结果数组中。
1.8.7 中的数组差异也是这样实现的。对 String 的更改只会在 irb 中引起问题(而不是在普通的 ruby 脚本中)。
source code for
Array#-
.It appears that rather than testing for equality, a hash is made from the second array. Anything not contained in that array is pushed into the resultant array.
Array difference in 1.8.7 is implemented this way also. The changes to String only cause problems in irb (not in a plain ruby script).