How to compare strings using the spaceship operator (<=>) in Ruby
Overview
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:
-1if stringbis smaller.0if they are both equal.1if string b is larger.nilor nothing if they are not comparable. E.g., if one is a string and the other a number.
Syntax
str1 <=> str2
Parameters
-
str1: This is the first of the strings to compare. -
str2: This is the second string you want to compare with the first string.
Return value
An integer value is returned. Nothing is returned if they are not comparable.
Code
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
Explanation
-
From the code above,
str2is greater thanstr1because"b"comes after"a". -
str3is greater thanstr4because the first letter ofstr3,"E"is greater than the first letter ofstr4, which is"C". -
Line 16 prints
0becausestr5also has the same value as"Meta". So, they are both equal.