Taymon Taymon - 1 year ago 70
Ruby Question

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.

Answer Source

This doesn't require conversion to set:

a.uniq.sort == b.uniq.sort
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download