I'm familiar with Ruby's include?
method for strings, but how can I check a string for multiple things?
Specifically, I need to check if a string contains "Fwd:" or "FW:" (and should be case insensitive)
Example string would be: "FWD: Your Amazon.com Order Has Shipped"
Using regular expressions, we can easily check multiple substrings in a single-line statement. We use the findall() method of the re module to get all the matches as a list of strings and pass it to any() method to get the result in True or False.
A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.
Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled.
the_string =~ /fwd:|fw:/i
You could also use something like
%w(fwd: fw:).any? {|str| the_string.downcase.include? str}
Though personally I like the version using the regex better in this case (especially as you have to call downcase in the second one to make it case insensitive).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With