nobilik nobilik - 1 year ago 57
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

What is the Rails or Ruby way to do 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