How to find common words in two strings with Ruby

1 Answer

0 votes
#
# Normalize a string:
# - Convert letters to lowercase
# - Replace any non-letter with a space
# This ensures consistent word comparison.
#
def normalize(text)
  result = text.chars.map do |ch|
    if ch.match?(/[A-Za-z]/)
      ch.downcase
    else
      " "
    end
  end

  result.join
end

#
# Extract words from a string.
#
# This function:
# - Normalizes the input
# - Splits on whitespace
# - Filters out empty entries
# - Returns a Set for fast lookup and automatic duplicate removal
#
def extract_words(text)
  normalized = normalize(text)
  parts = normalized.split(/\s+/)

  require "set"
  Set.new(parts)
end

#
# Find common words between two strings.
#
# This function:
# - Extracts words from both strings
# - Uses set intersection for efficiency
# - Returns a Set containing the common words
#
def find_common_words(a, b)
  words_a = extract_words(a)
  words_b = extract_words(b)

  words_a & words_b
end

#
# Main execution
#
s1 = "The quick brown fox jumps over the lazy dog."
s2 = "A lazy dog sleeps while the quick fox runs away."

common = find_common_words(s1, s2)

puts "Common words:"
common.each { |w| puts w }



=begin
run:

Common words:
the
quick
fox
lazy
dog

=end

 



answered Sep 11 by avibootz
...