2012-02-29 67 views
2

我正在掃描產品名稱以檢查其中是否存在特定的字符串。現在它適用於單個字符串,但我怎樣才能掃描多個字符串?例如我想掃描兩個蘋果和微軟如何掃描多個字符串的文本?

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

如果檢測到字符串,我得到[「蘋果」] 如果沒有的話則返回nil []

回答

5

您可以使用regex alternation

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

如果你需要知道的是字符串是否包含任何指定的字符串,你應該更好地使用單個匹配=~,而不是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 
+0

真棒,我很感激! – ahuang7 2012-02-29 08:48:40

2

你也可以完全跳過的正則表達式:

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

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