I've written a phrase-matching method to return the longest matching phrase from two Strings in Ruby. My method looks like this and works as expected:
class String
def phrase_in_common(other)
n = [size, other.size].min
while n > 0 do
other_words = other.downcase.split.each_cons(n)
string_words = split.each_cons(n)
matching_words = string_words.find { |cons_words| other_words.include?(cons_words.map(&:downcase)) }
return matching_words&.join(' ') if matching_words
n -= 1
end
end
end
>> string = "Hello world, please come to my house next week"
>> other = "Hello friends, please come to my party next week"
>> string.phrase_in_common(other)
=> "please come to my"
My question is, can (and should) this be accomplished in a more Ruby way, perhaps by replacing the while with an Enumerable method of some kind?
To clarify, the phrase-matching should be based on words, so for example:
>> "this phrase".phrase_in_common("his phrase")
=> "phrase"
Also, note that the method is case-insensitive in matching and uses the case of the subject String for the return value:
>> "Greatest Show On The Earth".phrase_in_common("Silliest Show on the Earth")
=> "Show On The Earth"
\wcharacters? \$\endgroup\$