To check if two arrays have the same elements regardless of order in Ruby, you can sort both arrays and then compare them element by element.
In this example,
arr1
and arr2
with the same elements but in different order.sort
method.arrays_equal
that checks if the sorted arrays are equal.arrays_equal
to compare the arrays and print the result.def arrays_equal(arr1, arr2)
arr1.sort == arr2.sort
end
arr1 = [1, 2, 3]
arr2 = [3, 1, 2]
puts arrays_equal(arr1, arr2)
true
In this example,
arr3
and arr4
with different elements.sort
method.arrays_equal
that checks if the sorted arrays are equal.arrays_equal
to compare the arrays and print the result.def arrays_equal(arr1, arr2)
arr1.sort == arr2.sort
end
arr3 = [1, 2, 3]
arr4 = [4, 5, 6]
puts arrays_equal(arr3, arr4)
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in Ruby language with well detailed examples.