How to Check if a Ruby String Ends With a Specific String?

In Ruby, you can check if a string ends with a particular suffix in the following ways:

You can use the String#end_with? method or a regular expression to check for multiple suffixes as well.

Using String#end_with?

To check if a string ends with a specified suffix, you can use the String#end_with? method in the following way:

puts "foobar".end_with?("bar") #=> true
puts "foobar".end_with?("foo") #=> false

The String#end_with? method checks for matches in a case-sensitive way, as you can see in the examples below:

puts "foobar".end_with?("Bar") #=> false
puts "foobar".end_with?("bAR") #=> false
# ...

To do a case-insensitive match, you can call the String#downcase method on the string first, to always compare against lowercase string:

puts "fooBar".downcase.end_with?("bar") #=> true
puts "fooBAR".downcase.end_with?("bar") #=> true
# ...

Using Regular Expression

You can specify a suffix to match at the end of a string using a regular expression like the following:

puts "foobar".match?(/bar$/) #=> true
puts "foobar".match?(/foo$/) #=> false

The $ sign at the end of the regular expression allows you to match the preceding string only at the end of the input string. If the specified suffix matches the end of the string, the String#match? method returns boolean true. Otherwise, false is returned.

If you don't specify the i flag, the regular expression will do a case-sensitive match:

puts "foobar".match?(/Bar$/) #=> false
puts "foobar".match?(/bAR$/) #=> false
puts "foobar".match?(/bAr$/) #=> false
# ...

If you wish to do a case-insensitive match instead, you can simply add the i flag to the regular expression, for example, like so:

puts "foobar".match?(/Bar$/i) #=> true
puts "foobar".match?(/bAR$/i) #=> true
puts "foobar".match?(/bAr$/i) #=> true
# ...

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.