Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two arrays ignoring element order in Ruby

I need to check whether two arrays contain the same data in any order. Using the imaginary compare method, I would like to do:

arr1 = [1,2,3,5,4] arr2 = [3,4,2,1,5] arr3 = [3,4,2,1,5,5]  arr1.compare(arr2) #true     arr1.compare(arr3) #false 

I used arr1.sort == arr2.sort, which appears to work, but is there a better way of doing this?

like image 341
SimonMayer Avatar asked Feb 01 '12 11:02

SimonMayer


People also ask

How do you compare two arrays in Ruby?

Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

How do you sort an array in Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.


1 Answers

The easiest way is to use intersections:

@array1 = [1,2,3,4,5] @array2 = [2,3,4,5,1] 

So the statement

@array2 & @array1 == @array2 

Will be true. This is the best solution if you want to check whether array1 contains array2 or the opposite (that is different). You're also not fiddling with your arrays or changing the order of the items. You can also compare the length of both arrays if you want them to be identical in size.

It's also the fastest way to do it (correct me if I'm wrong)

like image 129
MMM Avatar answered Sep 29 '22 12:09

MMM