How to Check if a Ruby String Starts With One of Multiple Prefixes?

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

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

Using String#start_with?

To check if a string starts with one of the specified prefixes, you can use the String#start_with? method in the following way:

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

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

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

puts "foobar".start_with?("Foo", "fOO", "fOo") #=> 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.start_with?("foo", "bar", "baz") #=> true
puts "fOObar".downcase.start_with?("foo", "bar", "baz") #=> true
# ...

Using Regular Expression

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

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

Using the ^ sign at the start of the regular expression matches the strings that follow only at the start of the input string. If any of the specified prefixes match the start 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?(/^(Foo|Baz|Qux)/) #=> false
puts "foobar".match?(/^(fOO|bAZ|qUX)/) #=> false
puts "foobar".match?(/^(fOo|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?(/^(Foo|Baz|Qux)/i) #=> true
puts "foobar".match?(/^(fOO|bAZ|qUX)/i) #=> true
puts "foobar".match?(/^(fOo|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.