Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 547
Zequez Avatar asked Sep 19 '11 21:09

Zequez


People also ask

How does an array work?

Arrays are extremely powerful data structures that store elements of the same type. The type of elements and the size of the array are fixed and defined when you create it. Memory is allocated immediately after the array is created and it's empty until you assign the values.

What is an array with example?

An array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. String[] array = new String[100];

How an array is formed?

Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

How does an array work in programming?

An array is a series of memory locations – or 'boxes' – each of which holds a single item of data, but with each box sharing the same name. All data in an array must be of the same data type . This would work, but there is a better way. It is much simpler to keep all the related data under one name.


1 Answers

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).

like image 193
cam Avatar answered Nov 14 '22 16:11

cam