To check if two arrays are equal in Ruby, you can use the ==
operator for arrays with the same elements and manually compare elements for arrays with different elements.
In this example,
arr1
and arr2
with the same elements.==
operator to check if the arrays are equal and store the result in the variable equal1
.==
operator checks if two arrays have the same elements in the same order.equal1
to the console.arr1 = [1, 2, 3]
arr2 = [1, 2, 3]
equal1 = arr1 == arr2
puts "Arrays are equal: #{equal1}"
Arrays are equal: true
In this example,
arr3
and arr4
with different elements.equal2
.equal2
is set to true
; otherwise, it's set to false
.equal2
to the console.arr3 = [1, 2, 3]
arr4 = [3, 2, 1]
equal2 = true
arr3.each_with_index do |elem, index|
unless elem == arr4[index]
equal2 = false
break
end
end
puts "Arrays are equal: #{equal2}"
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in Ruby language with well detailed examples.