Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays in Ruby

Tags:

ruby

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.

like image 573
Steve Lane Avatar asked Apr 20 '13 12:04

Steve Lane


People also ask

How do you compare two arrays in Ruby?

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 .

How do you find the common element in two arrays in Ruby?

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.


1 Answers

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
like image 103
Stefan Avatar answered Sep 28 '22 06:09

Stefan