Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
communitycreator

How to check if two arrays are equal in Ruby

okwudili onyejiaku

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.

Syntax

array1 == array2

Parameters

array1: This is the first array you want to compare.

array2: This is the second array you want to compare.

Return value

The value returned is bool which is true if the arrays are equal and false if otherwise.

Code example

In the example below, we created arrays and compared if they are equal using the == operator:

# Create arrays
arr1 = [1, 2, 3]
arr2 = ["a", "b", "c"]
arr3 = ["Python", "Ruby", "Java"]
arr4 = [true, false]
arr5 = [nil, "nil", "false"]

# compare arrays
a = arr1 == [3, 4]           # false
b = arr2 == ["a", "b", "c"]  # true
c = arr3 == ["C++", "C"]     # false
d = arr4 == [false, true]    # false
e = arr5 == ["nil", ""]      # false

# print values returned
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"

Explanation

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.

RELATED TAGS

array
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring