How to sort the words in a string with Ruby

1 Answer

0 votes
# Function to sort the words in a string
def sort_words_in_string(s)
  # Create an array to hold the words
  words = s.split(" ")   # Words are separated by spaces

  # Enable automatic alphabetical sorting
  words.sort!

  # Optional: ignore duplicate words
  # (Ruby's `uniq` removes duplicates)
  words = words.uniq

  # Join the sorted words back into a single string
  words.join(" ")
end

# Test the function
puts sort_words_in_string("the quick brown fox jumps over the lazy dog")


=begin
run:

brown dog fox jumps lazy over quick the

=end

 



answered May 21 by avibootz
...