Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two arrays have the same contents (in any order)

I'm using Ruby 1.8.6 with Rails 1.2.3, and need to determine whether two arrays have the same elements, regardless of whether or not they're in the same order. One of the arrays is guaranteed not to contain duplicates (the other might, in which case the answer is no).

My first thought was

require 'set' a.to_set == b.to_set 

but I was wondering if there was a more efficient or idiomatic way of doing it.

like image 333
Taymon Avatar asked Jun 06 '12 18:06

Taymon


People also ask

How do you check if two arrays have the same elements in the same order?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you check if an array has the same value?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.

How do I compare the contents of two arrays?

Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object.


1 Answers

This doesn't require conversion to set:

a.sort == b.sort 
like image 53
Mori Avatar answered Sep 28 '22 07:09

Mori