Darshan.Ishaya
11/23/2006 2:55:00 AM
Well, I'm new to Ruby, but it was an interesting question so I gave it
a stab. My first idea was
a.sort == b.sort
which works if all the elements of an array of of the same class. But
if you mix objects of different class (like you example with Fixnums
and a String), sort() craps out on it. You can pass a block to sort,
but I couldn't think of a good way to use that to our advantage. So I
resorted to more of a brute force method:
def same_elems?(array1, array2)
return false unless array1.length == array2.length
tmp = array2.clone
array1.each do |item|
if i = tmp.index(item) then tmp.delete_at(i) end
end
return tmp.empty?
end
As far as I can tell it meets all of your criteria.
Darshan
Daniel N wrote:
> I want to check to see if two arrays contain the same values.
> That is, are they the same array but not in the same order.
>
> Example
> equal
> [1,2,3,4,"abc"] should equal [2,3,1,"abc",4] and all the other different
> orders that are possible
>
> This should not be equal
> [1,2,3] and [1,1,2,3]
> [1,2,3,nil] and [nil, nil, nil, 1,2,1,3,2]
>
> At first I thought of
> (( array1 | array2 ) - array1).size == 0
>
> but this does not take into account duplicate values and the should not
> equals do equal :(. In fact I have not been able work out how to use any of
> the standard array, or Enumerable methods in such a way I can check if two
> arrays contain the same values as well as taking into account duplicates.
>
> Any pointers?
>
> Cheers
> Daniel
>
> ------=_Part_45042_23178773.1164243892803--