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(phrase),它应该返回

["chrome", "firefox", "ie"]

如果这句话是:

 phrase_2 = "I don't use Opera"

如果我们运行 little_parser(phrase_2),它应该只返回:

["opera"]

我该如何以最简单的方式做到这一点?

4

3 回答 3

3

您可以遍历浏览器并用于str.include?挑选出字符串中的项目:

def little_parser(str)
  browsers = ["chrome", "firefox", "ie", "opera"]
  browsers.select { |browser| str.include?(browser) }
end
于 2013-05-23T04:14:43.583 回答
1
def little_parser(str)
  str.scan(/\w+/).map(&:downcase) & browsers
end
于 2013-05-23T04:20:47.013 回答
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"]
于 2013-05-23T04:21:58.860 回答