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.
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.
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];
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With