Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to compare arrays with the spaceship (<=>) operator in Ruby

okwudili onyejiaku

The spaceship operator <=>

The spaceship operator <=> is used to compare arrays in Ruby. The spaceship operator checks which of two arrays is greater, which is lesser, or if they are equal.

When arrays a and b are compared, any of the following three values can be returned:

  1. -1: If a is less than b.
  2. 1: If a is greater than b.
  3. 0: If a is equal to b.

Arrays are compared by comparing the first elements of the two arrays, followed by the other elements, pair by pair. When there is a non-zero, that result is returned for the whole array comparison.

If the elements are all equal, then the result will be based on the lengths of the arrays.

Note: If the two arrays are not comparable, nil or nothing is returned.

Syntax

array1 <=> array2

Parameters

  • array1: One of the two arrays that you want to compare.
  • array2: The array that you want to compare with the first array.

Return value

The return value is either 1, 0, or -1. The spaceship operator returns 1 if array a is greater than array b, 0 if they are equal, and -1 if array a is less than array b.

Code example

Let’s take a look at how to use the spaceship comparison operator. We first create some arrays, call the operator on them, and pass the returned values to variables. Then, we display the returned value on the console.

# create arrays
arr1 = [1, 2, 3]
arr2 = [1, 2, 3]

arr3 = ["a", "b", "c"]
arr4 = ["a", "c", "d"]

arr5 = [1, 2]
arr6 = ["a", "b"]

# compare arrays
a = arr1 <=> arr2
b = arr3 <=> arr4
c = arr5 <=> arr6

# print out returned values
puts a    # 0
puts b    # -1
puts c    # nil or nothing

Explanation

In the code above, 0 is the result of the comparison between arr1 and arr2 because they are equal.

The operator returns -1 for arr3 and arr4 because arr3 is less than arr4. This is because when “b” from arr3 is compared to “c” of arr4, “c” is greater.

Lastly, nothing is returned when arr5 and arr6 are compared because they are not comparable. arr5 is an array of integer values and arr6 is an array of alphabets.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring