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
.
array1 == array2
array1
: This is the first array you want to compare.
array2
: This is the second array you want to compare.
The value returned is bool
which is true
if the arrays are equal and false
if otherwise.
In the example below, we created arrays and compared if they are equal using the ==
operator:
# Create arraysarr1 = [1, 2, 3]arr2 = ["a", "b", "c"]arr3 = ["Python", "Ruby", "Java"]arr4 = [true, false]arr5 = [nil, "nil", "false"]# compare arraysa = arr1 == [3, 4] # falseb = arr2 == ["a", "b", "c"] # truec = arr3 == ["C++", "C"] # falsed = arr4 == [false, true] # falsee = arr5 == ["nil", ""] # false# print values returnedputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"puts "#{e}"
In line number 2 to 6: We have declared different types of arrays.
In line number 8 to 13: We have compared these arrays.
In line number 16 to 20: We have simply printed the comparison results of these areas using puts
.