aidy
#1
Hi Guys
I have compared an array and ‘0’ is being returned which indicates to
me that that array is equal
p t = $ie.table(:index, ‘2’).to_a.flatten
p t <=> [“HINCKLEY”, “HINDHEAD”, “HINTON ST GEORGE”]
Now would it be possible for me to extract any differences from this
array (that is, when the array is not equal)?
Or should I really be using Test::Unit: to assert array equality?
aidy
aidy
#2
On 17.08.2006 13:32, aidy wrote:
Or should I really be using Test::Unit: to assert array equality?
You can use Array#zip (block form) to determine any differences.
[“HINCKLEY”, “HINDHEAD”, “HINTON ST GEORGE”].zip(t) do |a,b|
if a != b
print "Difference: ", a.inspect, " ", b.inspect, “\n”
end
end
Kind regards
robert
aidy
#3
Robert K. schrieb:
You can use Array#zip (block form) to determine any differences.
[“HINCKLEY”, “HINDHEAD”, “HINTON ST GEORGE”].zip(t) do |a,b|
if a != b
print "Difference: ", a.inspect, " ", b.inspect, “\n”
end
end
But note that this doesn’t work if the second array contains more
elements than the first:
[1].zip [1, 2, 3] # => [[1, 1]]
It is also problematic if the arrays can contain nil:
[nil, nil, nil].zip [nil] # => [[nil, nil], [nil, nil], [nil, nil]]
Regards,
Pit
aidy
#4
You could always add an XOR function to the Array class.
class Array
def XOR(i)
return (i | self) - (i & self)
end
def ^(i)
return XOR(i)
end
end
It should be there already anyway, even if it is just syntactic sugar…
aidy
#5
Now would it be possible for me to extract any differences from this
array (that is, when the array is not equal)?
Or should I really be using Test::Unit: to assert array equality?
aidy
t = [2, 3, 4, 5]
use == if you want to test for equality
p t == [2, 3, 4, 5] # => true
if t != [3, 4, 5, 6]
you may use the array set methods to show the differences
p t - [3, 4, 5, 6] #=> [2]
p [3, 4, 5, 6] - t #=> [6]
p ([3, 4, 5, 6] | t) - ([3, 4, 5, 6] & t) #=> [6, 2]
end
cheers
Simon