Kernel#printf
printf(format_string [, arguments...]) -> nil Returns:
nil · Updated March 13, 2026 · Kernel Methods output formatting strings printing
The printf method outputs a formatted string to STDOUT. It uses format specifiers similar to Cās printf function, allowing precise control over how numbers, strings, and other values are displayed.
Basic Format Specifiers
# %d - Integer
printf("%d", 42) # => 42
# %f - Float
printf("%.2f", 3.14159) # => 3.14
# %s - String
printf("%s", "hello") # => hello
# %x - Hexadecimal
printf("%x", 255) # => ff
printf("%X", 255) # => FF
# %o - Octal
printf("%o", 64) # => 100
# %b - Binary
printf("%b", 10) # => 1010
Width and Precision
# Minimum width
printf("%5d", 42) # => " 42"
printf("%-5d", 42) # => "42 "
# Precision for floats
printf("%.3f", 3.14159) # => 3.142
printf("%.0f", 3.7) # => 4
# Minimum and maximum width
printf("%8.2f", 3.14) # => " 3.14"
Multiple Arguments
# Multiple values
printf("Name: %s, Age: %d", "Alice", 30)
# => Name: Alice, Age: 30
printf("%d + %d = %d", 1, 2, 3)
# => 1 + 2 = 3
Practical Examples
Table Formatting
# Align columns
printf("%-15s %10s\n", "Product", "Price")
printf("%-15s %10.2f\n", "Apple", 1.50)
printf("%-15s %10.2f\n", "Banana", 0.75)
printf("%-15s %10.2f\n", "Cherry", 12.99)
# Output:
# Product Price
# Apple 1.50
# Banana 0.75
# Cherry 12.99
Hex Dump
# Memory dump style output
data = [72, 101, 108, 108, 111] # "Hello"
data.each { |b| printf("%02X ", b) }
# => 48 65 6C 6C 6F
Number Formatting
# Thousand separators
printf("%,d", 1234567) # => 1,234,567
# Percentage
printf("%.1f%%", 0.75) # => 75.0%
# Scientific notation
printf("%.2e", 1234) # => 1.23e+03
Padding with Zeroes
printf("%05d", 42) # => 00042
printf("%08.2f", 3.14) # => 00003.14
Using Named Arguments (Ruby 2.6+)
printf("%{name} is %{age} years old", name: "Bob", age: 25)
# => Bob is 25 years old
Comparison with Other Output Methods
puts "hello" # Adds newline
print "hello" # No newline
printf "hello" # With formatting
# printf returns nil
result = printf("Value: %d", 42)
puts result # => nil
Special Characters
# Escape sequences
printf("Tab:\tNext\n")
printf("Newline:\nDone\n")
# Literal percent sign
printf("100%% complete\n") # => 100% complete
The printf method is powerful for creating formatted output, especially when you need precise control over number formatting, alignment, or table-like displays.