Comparing two arrays ignoring element order in Ruby

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)


Sorting the arrays prior to comparing them is O(n log n). Moreover, as Victor points out, you'll run into trouble if the array contains non-sortable objects. It's faster to compare histograms, O(n).

You'll find Enumerable#frequency in Facets, but implement it yourself, which is pretty straightforward, if you prefer to avoid adding more dependencies:

require 'facets'
[1, 2, 1].frequency == [2, 1, 1].frequency 
#=> true

If you know that there are no repetitions in any of the arrays (i.e., all the elements are unique or you don't care), using sets is straight forward and readable:

Set.new(array1) == Set.new(array2)

You can actually implement this #compare method by monkey patching the Array class like this:

class Array
  def compare(other)
    sort == other.sort
  end
end

Keep in mind that monkey patching is rarely considered a good practice and you should be cautious when using it.

There's probably is a better way to do this, but that's what came to mind. Hope it helps!


The most elegant way I have found:

arr1 = [1,2,3,5,4]
arr2 = [3,4,2,1,5]
arr3 = [3,4,2,1,5,5]


(arr1 - arr2).empty? 
=> true

(arr3 - arr2).empty?
=> false