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.
b are compared, any of the following three values can be returned:
ais less than
ais greater than
ais equal to
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.
array1 <=> array2
array1: One of the two arrays that you want to compare.
array2: The array that you want to compare with the first array.
The return value is either
-1. The spaceship operator returns
1 if array
a is greater than array
0 if they are equal, and
-1 if array
a is less than array
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
In the code above,
0 is the result of the comparison between
arr2 because they are equal.
The operator returns
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
arr6 are compared because they are not comparable.
arr5 is an array of integer values and
arr6 is an array of alphabets.
View all Courses