How does Array # - (subtract operator) compare elements for equality?

When I call Array#- , it does not call the comparison method for the lines that I am 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 does Array#- do?

In addition, I am using Ruby 1.9.2p290. In 1.8.7, it causes an infinite loop.

+7
source share
1 answer

source code for Array#- .

It seems that instead of checking for equality, the hash is made from a second array. Everything that is not contained in this array is placed in the resulting array.

The difference in 1.8.7 is implemented similarly. Changes to String only cause problems in irb (not in a regular ruby ​​script).

+5
source

All Articles