Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to check if a string contains multiple items?

Tags:

string

ruby

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"

like image 824
Shpigford Avatar asked Jan 20 '10 20:01

Shpigford


People also ask

How do I check if a string contains multiple substrings?

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.

How do you find the part of a string in Ruby?

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.

What is whitespace in Ruby?

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.


1 Answers

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).

like image 68
sepp2k Avatar answered Sep 25 '22 03:09

sepp2k