Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,596 questions

55,330 answers

573 users

How to remove duplicate words from free‑text in Ruby

1 Answer

0 votes
require "set"

#
# split_words
#
# Splits free text into words using a Unicode-aware regex.
#
# Ruby supports Unicode properties:
#   \p{L}  → any Unicode letter
#   [^\p{L}]+ → any sequence of NON-letters
#
# This gives correct splitting for multilingual free text.
#
def split_words(text)
  trimmed = text.strip

  # Split on any sequence of non-letter characters
  parts = trimmed.split(/[^\p{L}]+/)

  parts
end

#
# remove_duplicate_words
#
# Removes duplicate words while preserving:
#   - original order
#   - original casing of first occurrence
#   - case-insensitive comparison
#
# Uses Set for O(1) lookup.
#
def remove_duplicate_words(text)
  words = split_words(text)

  seen   = Set.new
  unique = []

  words.each do |word|
    next if word.empty?

    key = word.downcase  # Unicode-aware lowercase

    unless seen.include?(key)
      seen.add(key)
      unique << word      # preserve original casing
    end
  end

  # Reassemble into a space-separated string
  unique.join(" ")
end

#
# Program entry point
#
input =
  "Hello, hello! This is a test. A TEST, hello universe...   " \
  "UNIVERSE! Hello; ***  Is Anybody There?"

output = remove_duplicate_words(input)

puts output



=begin
run:

Hello This is a test universe Anybody There

=end

 



answered 4 days ago by avibootz
...