Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
ruby
compare
communitycreator

How to compare strings using the spaceship operator (<=>) in Ruby

okwudili onyejiaku

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:

  1. -1 if string b is smaller.
  2. 0 if they are both equal.
  3. 1 if string b is larger.
  4. nil or 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 strings
str1 = "a"
str2 = "b"
str3 = "Educative"
str4 = "Chrome"
str5 = "Meta"

# compare the strings
a = str1 <=> str2     # str2 is greater
b = str3 <=> str4     # str3 is greater
c = str5 <=> "Meta"   # they are the same

# print returned values
puts a  # -1      
puts b  # 1
puts c  # 0
Comparing strings with <=> operator

Explanation

  • 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.

RELATED TAGS

string
ruby
compare
communitycreator
RELATED COURSES

View all Courses

Keep Exploring