Kernel#format
format(format_string [, arguments...]) -> string Returns:
String · Updated March 13, 2026 · Kernel Methods strings formatting output sprintf
The format method (alias for sprintf) creates a formatted string using specifiers similar to Cās printf. It provides precise control over string formatting.
Basic Format Specifiers
# %d - Integer
format("%d", 42) # => "42"
# %f - Float
format("%.2f", 3.14159) # => "3.14"
# %s - String
format("%s", "hello") # => "hello"
# %x - Hex
format("%x", 255) # => "ff"
Width and Precision
# Minimum width
format("%5d", 42) # => " 42"
# Left align
format("%-5d", 42) # => "42 "
# Precision
format("%.3f", 3.14159) # => "3.142"
Multiple Arguments
format("Name: %s, Age: %d", "Alice", 30)
# => "Name: Alice, Age: 30"
Practical Examples
Currency Formatting
def format_currency(amount)
format("$%.2f", amount)
end
format_currency(19.99) # => "$19.99"
format_currency(1000.00) # => "$1000.00"
Table Generation
headers = ["Name", "Score"]
rows = [["Alice", 95], ["Bob", 87]]
puts format("%-10s %5s", *headers)
rows.each { |r| puts format("%-10s %5d", *r) }
Padding
# Zero-padded
format("%05d", 42) # => "00042"
# Hex with padding
format("%08X", 255) # => "000000FF"
Named Parameters (Ruby 2.6+)
format("%{name} is %{age} years old", name: "Bob", age: 25)
# => "Bob is 25 years old"
Flags
# +: Always show sign
format("%+d", 5) # => "+5"
format("%+d", -5) # => "-5"
# Space: Space for positive
format("% d", 5) # => " 5"
# #: Alternate form
format("%#x", 255) # => "0xff"
format("%#o", 64) # => "0100"
Array Arguments
# Using * to expand array
args = ["Hello", 42]
format("Message: %s, Code: %d", *args)
Percentage
# Literal percent
format("100%%") # => "100%"
format("%.0f%%", 75.5) # => "76%"
Common Use Cases
- Generating formatted output
- String interpolation with control
- Building reports
- Internationalization