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

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

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

Using String#start_with?

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

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

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

puts "foobar".start_with?("Foo") #=> false
puts "foobar".start_with?("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") #=> true
puts "fOObar".downcase.start_with?("foo") #=> true
# ...

Using Regular Expression

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

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

The ^ sign at the start of the regular expression allows you to match the string that follows only at the start of the input string. If the specified prefix matches the start 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?(/^Foo/) #=> false
puts "foobar".match?(/^fOO/) #=> false
puts "foobar".match?(/^fOo/) #=> 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/i) #=> true
puts "foobar".match?(/^fOO/i) #=> true
puts "foobar".match?(/^fOo/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.