nobilik nobilik - 5 months ago 8
Ruby Question

How to make filter that will pass a message only if it contains one of words in list?

I want to filter incoming info to read news (for example) that have one of words that I've specified.
Specified words:

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


news:

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


Ok, second one is the message that I want to read.
What I think:

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


The question is what is the Rails, Ruby way to make 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”.