How to find the largest and the smallest word in a string with Ruby

1 Answer

0 votes
# Finds the largest and smallest words in a given string.
# 
# @param s [String] The input string containing words.
# @return [Array<String>] An array containing [largest_word, smallest_word].
def find_largest_and_smallest_words(s)
  # Split the string into an array of words based on whitespace
  words = s.split
  
  # Return empty strings if the input contains no words
  return ["", ""] if words.empty?

  # Use Ruby's idiomatic max_by and min_by to find elements based on length
  largest = words.max_by(&:length)
  smallest = words.min_by(&:length)

  [largest, smallest]
end

def main
  s = "Ruby is a general-purpose programming language with productivity and simplicity. "

  # Ruby supports parallel assignment, matching Go's multiple return values behavior
  largest, smallest = find_largest_and_smallest_words(s)

  puts "Largest word: #{largest}"
  puts "Smallest word: #{smallest}"
end

# Execute main if the script is run directly
if __FILE__ == $0
  main
end


# run:
#
# Largest word: general-purpose
# Smallest word: a
# 

 



answered 1 day ago by avibootz
...