user2968505 user2968505 - 10 days ago 5
Ruby Question

Ruby, how to find if a keyword from a list of keywords was the only one to appear in a string

I have list of key words, and i have a big string,. What i am interested in finding out is which keyword if any was the only one to appear in this string, so if more than one keyword from the list was in the string, then it gives nothing but if only 1 keyword from the list appeared i want to know that (how many times this single keyword was repeated doesn't matter). I am going to do this for multiple big strings.

Example as requested :

keywords=['cat','dog','mouse']

string1 = 'cat ate dog food'
string2 = 'dog chased cat'
string3 = 'my cat is chasing a mouse'
string4 = 'mouse ran away, mouse mouse mouse'

output for string1: false
output for string2: false
output for string3: false
output for string4: 'mouse'

Answer
def only_one(str, keywords)
  result = nil
  count = keywords.count { |k|
    result = k if str.include?(k)
  }
  count == 1 ? result : false
end

Enumerable#count will count how many times its block is truthy. The last expression of the block is a conditional assignment; it will produce nil if it is falsy, and the new value of result if truthy. result will always contain a truthy value here because all keywords are strings, and all strings are truthy. At the end, we just check whether there was a single