How to compare arrays with the spaceship (<=>) operator in Ruby
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: Ifais less thanb.1: Ifais greater thanb.0: Ifais equal tob.
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 arraysarr1 = [1, 2, 3]arr2 = [1, 2, 3]arr3 = ["a", "b", "c"]arr4 = ["a", "c", "d"]arr5 = [1, 2]arr6 = ["a", "b"]# compare arraysa = arr1 <=> arr2b = arr3 <=> arr4c = arr5 <=> arr6# print out returned valuesputs a # 0puts b # -1puts 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.