2

I'm scanning through a product name to check if a specific string exists in it. Right now it works for a single string, but how can I can scan for multiple strings? e.g. i'd like to scan for both apple and microsoft

product.name.downcase.scan(/apple/)

If the string is detected i get ["apple"] if not then it returns nil [ ]

2 Answers 2

5

You can use regex alternation:

product.name.downcase.scan(/apple|microsoft/)

If all you need to know is whether the string contains any of the specified strings, you should better use single match =~ instead of scan.

str = 'microsoft, apple and microsoft once again'

res = str.scan /apple|microsoft/ # => res = ["microsoft", "apple", "microsoft"]
# do smth with res

# or
if str =~ /apple|microsoft/
  # do smth
end
Sign up to request clarification or add additional context in comments.

Comments

2

You could also skip regular expressions altogether:

['apple', 'pear', 'orange'].any?{|s| product.name.downcase.match(s)}

or

['apple', 'pear', 'orange'].any?{|s| product.name.downcase[s]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.