Increasingly Functional.
by Joshua Miller | on Twitter | on the web | on github

Testing Array "Equality" In Ruby

September 15th 2010

Tagged: ruby

I frequently run into situations in both Test::Unit and RSpec where I want to assert that two arrays are equal, but order doesn't matter; i.e., set equality rather than array equality.

In RSpec, you can do the following:

[1, 2].should =~ [2, 1]

If you are using Shoulda with Test::Unit, you get:

assert_same_elements([1, 2], [2, 1])

If not, a quick helper method could look like:

def same_elements?(array_one, array_two)
  ((array_one - array_two) + (array_two - array_one)).empty?