Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Retrieve a Set of String within a String

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?

like image 255
Chim Kan Avatar asked Jan 26 '26 13:01

Chim Kan


2 Answers

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
like image 141
Dylan Markow Avatar answered Jan 28 '26 06:01

Dylan Markow


def little_parser(str)
  str.scan(/\w+/).map(&:downcase) & browsers
end
like image 34
sawa Avatar answered Jan 28 '26 05:01

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!