3

I have the following issue.

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

If we use the method little_parser( phrase ), it should return

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

If the phrase was:

 phrase_2 = "I don't use Opera"

If we run little_parser( phrase_2 ), it should return only:

["opera"]

How do I do that in the simplest way?

1

3 Answers 3

3

You could iterate through the browsers and use str.include? to single out the items which are in the string:

def little_parser(str)
  browsers = ["chrome", "firefox", "ie", "opera"]
  browsers.select { |browser| str.include?(browser) }
end
Sign up to request clarification or add additional context in comments.

1 Comment

You'd probably want to add downcase as well.
1
def little_parser(str)
  str.scan(/\w+/).map(&:downcase) & browsers
end

1 Comment

this will not work as per the OPs array phrase, need to have downcase method.
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"]

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.