String#capitalize
str.capitalize -> string String#capitalize returns a new string with the first character converted to uppercase and all remaining characters converted to lowercase. It is useful for formatting names, titles, and other text that should start with a capital letter.
This method does not modify the original string. It always returns a fresh string object.
Syntax
string.capitalize
Parameters
This method takes no parameters.
Examples
Basic usage
"hello".capitalize
# => "Hello"
"world".capitalize
# => "World"
All remaining characters become lowercase
Every character after the first gets forced to lowercase, regardless of its original case:
"HELLO".capitalize
# => "Hello"
"hELLO".capitalize
# => "Hello"
"HeLLo WoRLD".capitalize
# => "Hello world"
Non-alphabetic first character
If the first character is not an ASCII letter, no uppercasing occurs. Only the rest of the string gets lowercased:
"123abcDEF".capitalize
# => "123abcdef"
"!hello".capitalize
# => "!hello"
Empty string
"".capitalize
# => ""
Unicode and case mapping options
Modern Ruby applies Unicode-aware case mapping by default. That means non-ASCII letters can be capitalized correctly when the string encoding supports them.
"étude".capitalize
# => "Étude"
"über".capitalize
# => "Über"
If you specifically want ASCII-only behavior, pass the :ascii option:
"über".capitalize(:ascii)
# => "über"
Use the default behavior for normal text. Reach for :ascii only when you are intentionally processing ASCII-only identifiers, protocol values, or legacy data.
Mutating version
String#capitalize! modifies the string in place instead of returning a new one:
name = "alice"
name.capitalize!
# => "Alice"
name
# => "Alice"
Note that capitalize! returns nil if no change was needed:
str = "Alice"
str.capitalize!
# => nil
str
# => "Alice"
Common Patterns
Formatting user input
A common pattern is to combine capitalize with other string methods:
def format_name(name)
name.strip.capitalize
end
format_name(" john doe ")
# => "John doe"
This converts "john doe" to "John doe" — the first letter becomes uppercase and everything else becomes lowercase.