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.
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,
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.
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.
The value returned is an integer value.
In the example below, we will create some strings and compare them, using the
# 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,
str2 are the same, and so are
str1 is greater than
"H", the first letter of
str1, is greater than
"E", which is the first letter of
1 is returned.
View all Courses