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:

@array1.size == @array2.size && @array1 & @array2 == @array1

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)