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.
str.end_with?([suffixes]+)
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.
The value returned is a Boolean value. If the string ends with the suffix specified, it returns true
.
# create stringsstr1 = "Edpresso"str2 = "Developer"str3 = "Educative"str4 = "Welcome"# check suffixesa = str1.end_with?("sso")b = str2.end_with?("loper")c = str3.end_with?("sso")d = str4.end_with?("me")# print resultsputs a # trueputs b # trueputs c # falseputs d # true
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.
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.
# create some stringsstr1 = "Welcome"str2 = "Edpresso"# check suffixesa = str1.end_with?("come", "back") # trueb = str2.end_with?("and", "end") # false# print resultsputs aputs b
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"
.