How to convert a string to title case in Ruby

1 Answer

0 votes
# Converts a string to title case, normalizing any mixed or upper case text first.
# 
# @param input_string [String] The string to be converted.
# @return [String] The title-cased string.
# @raise [TypeError] If the input is not a String.
def to_title_case(input_string)
  # Guard clause: validate input type
  unless input_string.is_a?(String)
    raise TypeError, "Input must be a valid String."
  end

  # 1. Downcase the string to normalize any all-caps or mixed-case text
  # 2. Split the string into an array of words based on whitespace
  # 3. Capitalize each word individually
  # 4. Join the words back together with a single space
  input_string.downcase.split.map(&:capitalize).join(' ')
end

# --- Example Usage ---
if __FILE__ == $PROGRAM_NAME
  begin
    puts to_title_case("string programming functions")
    # Output: String Programming Functions

    puts to_title_case("STRING PROGRAMMING FUNCTIONS")
    # Output: String Programming Functions
  rescue StandardError => e
    warn "Error: #{e.message}"
    exit(1)
  end
end


# run:
#
# String Programming Functions
# String Programming Functions
#

 



answered 2 hours ago by avibootz
...