In Ruby, we can perform string comparison operations using various methods, as discussed in this tutorial.
1. Equality Operator
Two equal signs denote the equality operator in Ruby. It returns true if both objects are equal and false if otherwise.
var2 = “Hello”
var1 == var2
The equality operator does not care as long as both provided objects are valid strings
var2 = "Hello"
var2 == var1
If the strings are not equal, the equality operator will return false.
var2 = "World"
var1 == var2
You can do more than compare string variables. You can also compare a string literal as:
It is good to note that a numerical string is not directly comparable to an integer value.
2. Not Equal
The not equal operator, denoted as !=, returns true if the compared values are not equal and false if equal. It acts as a negation of the equality operator.
If the compared values are not equal, it returns true as:
3. Eql? Method
Ruby has a built-in string method called eql?. The eql? method checks if the values are equal in both length and content. The eql? method returns true if the compared values are equal or not.
In this case, both strings are equal in length and content.
The eql? method is case-sensitive and will return false if the casing is not equal
Unlike the equality operator that returns true when you compare an integer and float, the eql? method returns false as:
4. Equal? Method
Unlike the equality operator that checks if both values are equal, the equal? method checks if both operands reference the same object.
var2 = "hello"
You will notice that the method returns false as the values do not reference the same object. You can get this using object_id as:
An example of both operands pointing to the same object is as shown:
5. Spaceship Notation
Ruby also provides a way of comparing strings known as spaceship notation. We express this with a less than sign, an equal sign, and a greater than an operator.
The method returns 0 if the strings match -1 if the left operand is less than the right operand, and 1 if the right operand is greater than the left operand.
"HELLO" <=> "hello"
"hello" <=> "HELLO"
6. Casecmp method
To perform a case insensitive comparison, you can use the casecmp method. It has similar return values to spaceship notation.
The method ignores case-sensitivity and only compares the content of the strings.
7: Range Comparison
To compare if a character is within a specific range, we can use the range operator, donated using triple equal signs ===
("a".."g") === "z"
The operator returns true if the character is in the range and false if otherwise.
In this guide, we discussed various ways to compare strings in the Ruby language.
Thank you for reading!