How to compare strings in Ruby

Overview

In Ruby, strings are compared to see which one is larger or smaller, if they are equal to one another, or not comparable at all.

The casecmp() method is used to compare two strings while ignoring the case and returning 1, -1, or 0.

If a string, a, is larger than a string, b, then 1 is returned. If the latter is larger, then -1 is returned. If they are both the same, then 0 is returned. If they are not comparable, i.e., if one of them is not a string, nil or nothing is returned.

Syntax

str1.casecmp(str2)

Parameters

str1: This is the first of the two strings that we want to compare.

str2: This is the second of the two strings that we want to compare.

Return value

The value returned is an integer value.

Code example

In the example below, we will create some strings and compare them, using the casecmp() method.

# create some strings
str1 = "Hello"
str2 = "heLLO"
str3 = "edpresso"
str4 = "EDPRESSO"
# compare strings
a = str1.casecmp(str2)
b = str3.casecmp(str4)
c = str1.casecmp(str4)
# print out returned values
puts a
puts b
puts c

In the code given above, str1 and str2 are the same, and so are str3 and str4.

str1 is greater than str4 because "H", the first letter of str1, is greater than "E", which is the first letter of str4. Hence, 1 is returned.

Free Resources