user5724342 user5724342 - 7 months ago 14
Ruby Question

Check if a string contains an array of strings

I'm trying to find out if any of the words in the array

keywords
:

keywords = Array['hello', 'hi', 'home']


appear in
split
:

split = work.split(' ')


and for each
keyword
that appears in
split
, do something.

I have this code:

for keywords in splitDescription
score += 2
end


The code just gives me 2+ for each word in
split
, but I only want 2+ for each
keywords
appearing in
split
.

ndn ndn
Answer

Use set intersection on arrays (Array#&):

(splitDescription & keywords).each do |found_keyword|
  # something
end

If you know there might be some words repeating and you want to iterate over each occurrence:

splitDescription.select { |word| keywords.include?(word) }.each do |word|
  # something
end