The spaceship operator <=>
compares strings. Some strings are greater than the other, less than the other, or even equal to another.
With this operator, we can check which of the two strings is greater, less than, or equal. The string comparison is done alphabetically. E.g., “a” is less than “b” because alphabetically, “b” comes after it.
When comparing strings a
and b
with the spaceship operator <=>
, the following is returned:
-1
if string b
is smaller.0
if they are both equal.1
if string b is larger.nil
or nothing if they are not comparable. E.g., if one is a string and the other a number.str1 <=> str2
str1
: This is the first of the strings to compare.
str2
: This is the second string you want to compare with the first string.
An integer value is returned. Nothing is returned if they are not comparable.
In the code below, we demonstrate the use of the spaceship operator. We create some strings and compare them. Finally, we will output the returned values.
# create stringsstr1 = "a"str2 = "b"str3 = "Educative"str4 = "Chrome"str5 = "Meta"# compare the stringsa = str1 <=> str2 # str2 is greaterb = str3 <=> str4 # str3 is greaterc = str5 <=> "Meta" # they are the same# print returned valuesputs a # -1puts b # 1puts c # 0
From the code above, str2
is greater than str1
because "b"
comes after "a"
.
str3
is greater than str4
because the first letter of str3
, "E"
is greater than the first letter of str4
, which is "C"
.
Line 16 prints 0
because str5
also has the same value as "Meta"
. So, they are both equal.