nobilik nobilik - 5 months ago 11
Ruby Question

Filter that will pass a message only if it contains one of words in list

I want to filter incoming info:

news = [
'One day bla-bla-bla',
'Long time ago bla-bla',
]


and pass messages that have one of the words that I specify:

mywords = ['ago', 'time', 'hero']


I tried:

messages = []
news.each do |item|
mywords.each do |word|
if item.include?(word)
messages << item
return
end
end
end


What is the Rails or Ruby way to do it?

Answer
mywords = %w(ago time hero)
news = [
  'One day bla-bla-bla',
  'Long time ago bla-bla'
]
news.select { |n| mywords.any? { |w| n =~ /\b#{w}\b/ } }
#⇒ ["Long time ago bla-bla"]

or even better:

news.select { |n| n =~ Regexp.union(mywords) }
#⇒ ["Long time ago bla-bla"]

Please note, that my answer is more robust than others two [currently posted] since it will not match the news “Superman calls back” against word “man”.