How to Use the Ruby end_with? Method

09/26/2021

Contents

In this article, you will learn how to use the Ruby end_with? method.

Using the end_with? method

The end_with? method is a built-in Ruby method that can be used to check if a given string ends with a specified suffix or not. It returns a boolean value – true if the string ends with the specified suffix, and false otherwise.

Syntax

Here’s the basic syntax of the end_with? method:

string.end_with?(suffix)

where string is the string you want to check, and suffix is the string you want to check if it’s at the end of string.

Examples

Here are some examples of how to use the end_with? method:

"hello".end_with?("o")       # true
"hello".end_with?("llo")     # true
"hello".end_with?("l")       # false
"hello".end_with?("world")   # false

In the first example, the end_with? method returns true because the string “hello” ends with the letter “o”. In the second example, the method returns true because the string “hello” ends with the substring “llo”. In the third example, the method returns false because the string “hello” does not end with the letter “l”. And in the fourth example, the method returns false because the string “hello” does not end with the string “world”.

You can also pass multiple suffixes to the end_with? method, in which case it will return true if the string ends with any one of the specified suffixes. Here’s an example:

"hello".end_with?("o", "llo", "x")     # true

In this example, the end_with? method returns true because the string “hello” ends with either the letter “o” or the substring “llo”.

The end_with? method is case-sensitive, which means that it will return false if the case of the suffix does not match the case of the ending of the string. For example:

"hello".end_with?("O")       # false
"hello".end_with?("LLO")     # false

In these examples, the end_with? method returns false because the case of the suffixes does not match the case of the ending of the string.

Finally, it’s worth noting that the end_with? method is only available on string objects, and not on other types of objects. If you try to use it on a non-string object, you’ll get a NoMethodError.