Ruby检索一个字符串中的一组字符串

3
我有以下问题。
phrase = "I love Chrome and firefox, but I don't like ie."

browsers = ["chrome", "firefox", "ie", "opera"]

def little_parser ( str )

  # what's the best way to retrieve all the browsers within phrase?

end

如果我们使用小解析器(little_parser)的方法,它应该返回:
["chrome", "firefox", "ie"]

If the phrase was:

 phrase_2 = "I don't use Opera"

如果我们运行little_parser(phrase_2),它应该只返回以下内容:
["opera"]

最简单的方法是怎样做?


即“例如”可能有点模糊。http://zh.wikipedia.org/wiki/IE - oldergod
3个回答

3
你可以遍历浏览器并使用 str.include? 来筛选出字符串中的项目:
def little_parser(str)
  browsers = ["chrome", "firefox", "ie", "opera"]
  browsers.select { |browser| str.include?(browser) }
end

您可能还想添加 downcase - mind.blank

1
def little_parser(str)
  str.scan(/\w+/).map(&:downcase) & browsers
end

这段代码无法按照“OP”的数组“phrase”工作,需要使用“downcase”方法。 - Arup Rakshit

0
phrase = "I love Chrome and firefox, but I don't like ie."

browsers = ["chrome", "firefox", "ie", "opera"]
phrase.scan(/\w+/).select{|i| browsers.include? i.downcase }
#=> ["chrome", "firefox", "ie"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接