我有以下问题。
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"]
如果短语是:
phrase_2 = "I don't use Opera"
如果我们运行little_parser(phrase_2),它应该只返回:
["opera"]
我如何以最简单的方式做到这一点?
答案 0 :(得分:3)
您可以遍历浏览器并使用str.include?
来挑出字符串中的项目:
def little_parser(str)
browsers = ["chrome", "firefox", "ie", "opera"]
browsers.select { |browser| str.include?(browser) }
end
答案 1 :(得分:1)
def little_parser(str)
str.scan(/\w+/).map(&:downcase) & browsers
end
答案 2 :(得分: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"]