Ruby Program to Capitalize Each Word
split to break the string into words, then map(&:capitalize) to capitalize each word, and finally join(' ') to combine them back into a string, like this: str.split.map(&:capitalize).join(' ').Examples
How to Think About It
Algorithm
Code
puts 'Enter a sentence:' sentence = gets.chomp capitalized = sentence.split.map(&:capitalize).join(' ') puts capitalized
Dry Run
Let's trace the input 'hello ruby world' through the code.
Input string
'hello ruby world'
Split into words
['hello', 'ruby', 'world']
Capitalize each word
['Hello', 'Ruby', 'World']
Join words back
'Hello Ruby World'
| Original Word | Capitalized Word |
|---|---|
| hello | Hello |
| ruby | Ruby |
| world | World |
Why This Works
Step 1: Splitting the string
The split method breaks the sentence into individual words by spaces.
Step 2: Capitalizing words
The map(&:capitalize) applies the capitalize method to each word, making the first letter uppercase.
Step 3: Joining words
The join(' ') method combines the capitalized words back into a single string separated by spaces.
Alternative Approaches
require 'active_support/core_ext/string' puts 'hello ruby world'.titleize
sentence = 'hello ruby world'
capitalized = sentence.gsub(/\b\w/) { |c| c.upcase }
puts capitalizedComplexity: O(n) time, O(n) space
Time Complexity
The code processes each character once when splitting and capitalizing, so it runs in linear time relative to the string length.
Space Complexity
Extra space is used to store the list of words and the new capitalized string, so space is also linear in the input size.
Which Approach is Fastest?
The split-map-join approach is efficient and clear; regex can be slightly faster but less readable; ActiveSupport's titleize is convenient but adds dependency overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split.map(&:capitalize).join(' ') | O(n) | O(n) | General use, clear and readable |
| ActiveSupport titleize | O(n) | O(n) | Rails projects with ActiveSupport |
| Regex gsub | O(n) | O(n) | When avoiding splitting, but less readable |
split.map(&:capitalize).join(' ') for a quick and clear way to capitalize each word in Ruby.capitalize on the whole string, which only capitalizes the first letter of the entire sentence, not each word.