nobilik nobilik - 2 years ago 54
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[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

The question is what is the Rails, Ruby way to make it?

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

or even better: { |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”.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download