Reputation: 769
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.
Upvotes: 5
Views: 12849
Reputation: 14498
a1 = [1, 2, 3, 4]
a2 = [4, 2, 1, 3]
(a1 & a2).size == a1.size # => true
a3 = [1, 2, 3, 5]
(a1 & a3).size == a1.size # => false
Upvotes: 0
Reputation: 114138
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
Upvotes: 9
Reputation: 118261
[2,1].uniq.sort == [1,2].uniq.sort #=> true
[2,1,4].uniq.sort == [1,2].uniq.sort #=> false
or
a1 = [1,2,3]
a2 = [2,3,1]
p (a2-a1).empty? && (a1-a2).empty? #=> true
a1 = [1,2,3]
a2 = [4,3,1]
p (a2-a1).empty? && (a1-a2).empty? #=> false
a1 = [1,2,3]
a2 = [2,3,1,5]
p (a2-a1).empty? && (a1-a2).empty? #=> false
Upvotes: 6
Reputation: 76240
This would be extremely easy to write, I just wonder if there's a native idiom.
I'm afraid there's no native idiom for it.
If your arrays contains multiple values that you want to count on both arrays you'll have to use #sort to put them in the same order. Once you have done that you can easily compare them:
a.sort == b.sort
Otherwise you can use #uniq that will extract the unique values of the arrays (to make it faster) and use #sort like above:
a.uniq.sort == b.uniq.sort
Upvotes: 4