From: Daniel N Date: 2006-11-23T12:16:37+09:00 Subject: Re: Compare Array Values? ------=_Part_45967_22213845.1164251793295 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 11/23/06, Gabriele Marrone wrote: > > > On 23/nov/06, at 02:04, 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. > > def are_these_arrays_equal?(a1, a2) > return false if a1.size != a2.size > a2 = a2.dup # a2 will be modified, so let's duplicate it > for i1 in a1 > return false unless a2.include? i1 > # need to delete just the *first* occurrence of i1 in a2 > # (Array#delete deletes them all) > found = false > a2.delete_if {|i2| found = !found && i1 == i2 } > end > # a2 is now empty, since its size was equal to a1 size > return true > end > > This should work with multiple occurrences of the same object, > different objects (so different object_id) that seem to be equal (by > comparing them with ==), nil values (#find() is a bit tricky), > objects that do not respond to <=>. > Did I miss any case? I've made a list of the cases so far that I can think of, in a response to Davids post. The elements could be of arbitrary type. Anyway I think it's a bit slow (delete_if goes on even if we deleted > the only one we wanted to, moreover it duplicates a whole array), but > who cares? We're using ruby, we probably aren't looking for speed > anyway :P The case that I want to use it for is as a test helper so speed is not critical. I want to make sure that I don't have duplicate attributes in an association in rails that is not a straight forward use of validates_uniquness_of Thanx for your help... I'll give this one a go when I get to my computer. ------=_Part_45967_22213845.1164251793295--