What is the end_with?() method in Ruby?

Overview

The end_with?() method is used to check if a string ends with a specific string, also called a suffix.

Note: We can pass more than one suffix to the end_with?() method.

Syntax

str.end_with?([suffixes]+)

Parameters

  • str: The string we want to check to see if it ends with a particular string.

  • [suffixes]+: The suffix that we want to use and check to see if a string str ends with it. We can pass more than one suffix to the end_with? method.

Return value

The value returned is a Boolean value. If the string ends with the suffix specified, it returns true.

Example

# create strings
str1 = "Edpresso"
str2 = "Developer"
str3 = "Educative"
str4 = "Welcome"
# check suffixes
a = str1.end_with?("sso")
b = str2.end_with?("loper")
c = str3.end_with?("sso")
d = str4.end_with?("me")
# print results
puts a # true
puts b # true
puts c # false
puts d # true

Explanation

In the code above, we create some strings and check if the strings end with the suffixes we pass to them. All the strings end with the suffix passed to them except str3, which does not end with "sso", so a false value is returned.

Passing more than one suffix

When we pass more than one suffixes, if the string ends with at least one of the suffixes, a true value is returned. Otherwise, false is returned.

Let’s see an example below.

Example

# create some strings
str1 = "Welcome"
str2 = "Edpresso"
# check suffixes
a = str1.end_with?("come", "back") # true
b = str2.end_with?("and", "end") # false
# print results
puts a
puts b

Explanation

In the code above, we pass more than one suffix to both strings str1 and str2. If one of the suffixes is true, then a true value is returned. Otherwise, it will return false. Thus, str2 returns false because it does not end with "and" and "end".