How to Check if a Ruby String Ends With One of Multiple Suffixes?

In Ruby, you can check if a string ends with a particular suffix (out of many) in the following ways:

You can, of course, use the String#end_with? method or a regular expression to check for a single suffix as well (instead of multiple).

Using String#end_with?

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

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

As you can see from the example, if any one of the specified suffixes match the end of the string, boolean true is returned, or false otherwise.

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

puts "foobar".end_with?("Bar", "bAR", "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?("foo", "bar", "baz") #=> true
puts "fooBAR".downcase.end_with?("foo", "bar", "baz") #=> true
# ...

Using Regular Expression

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

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

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

Without specifying the i flag, the regular expression will do a case-sensitive match:

puts "foobar".match?(/(Bar|Baz|Qux)$/) #=> false
puts "foobar".match?(/(bAR|bAZ|qUX)$/) #=> false
puts "foobar".match?(/(bAr|bAz|qUx)$/) #=> 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|Baz|Qux)$/i) #=> true
puts "foobar".match?(/(bAR|bAZ|qUX)$/i) #=> true
puts "foobar".match?(/(bAr|bAz|qUx)$/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.