I'd like to know whether two Ruby arrays have the same elements, though not necessarily in the same order. Is there a native way to do this? The equality operators for Array seem to check whether the items are the same and the order is the same, and I need to relax the latter condition.
This would be extremely easy to write, I just wonder if there's a native idiom.
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. If the arrays are equal, a bool value is returned, which is either true or false .
We already know Array#intersection or Array#& methods which are used to find the common elements between arrays. The intersection or & methods return an empty array or array having the common elements in it as result.
If you don't have duplicate items either, you could use Set
instead of Array
:
Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.
Example:
require 'set'
s1 = Set.new [1, 2, 3] # -> #<Set: {1, 2, 3}>
s2 = [3, 2, 1].to_set # -> #<Set: {3, 2, 1}>
s1 == s2 # -> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With