How to Do Case-Insensitive Match With Ruby "String#start_with?()"?

By default the Ruby String#start_with? method does a case-sensitive match. However, you can perform a case-insensitive match by:

  1. Converting both, the string and the prefix(es) you are comparing, to lowercase (or uppercase), and;
  2. Applying String#start_with? on the converted strings.

For example:

puts "Foobar".downcase.start_with?("foo") #=> true
puts "fOObar".downcase.start_with?("foo", "bar", "baz") #=> true
# ...

In the examples above, the strings are converted to lowercase first (using the String#downcase method), and then String#start_with? is applied on the converted strings.

You can also use the String#upcase method instead of String#downcase if you prefer to convert the strings to uppercase instead of lowercase.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.