sprintf() / % Operator
A function and method for generating formatted strings. Commonly used for zero-padding numbers and controlling decimal places.
Syntax
# Use Kernel#sprintf (or format). sprintf(format_string, value, ...) format(format_string, value, ...) # The % operator provides a shorthand. format_string % value format_string % [value1, value2, ...]
Common Format Specifiers
| Specifier | Description |
|---|---|
| %d | Displays an integer in decimal. |
| %f | Displays a floating-point number. You can specify decimal places with %.2f. |
| %s | Displays a string. |
| %05d | Zero-pads the number to 5 digits. |
| %-10s | Left-aligns within a 10-character width (minus sign means left-align). |
| %x | Displays an integer in hexadecimal. |
| %b | Displays an integer in binary. |
| %% | Displays a literal % character. |
Sample Code
# Format an integer.
puts sprintf("%d", 42) # 42
puts sprintf("%05d", 42) # 00042 (zero-padded to 5 digits)
puts sprintf("%+d", 42) # +42 (show sign)
# The % operator does the same thing.
puts "%05d" % 42 # 00042
# Format a floating-point number.
puts sprintf("%.2f", 3.14159) # 3.14 (2 decimal places)
puts sprintf("%8.2f", 3.14) # " 3.14" (8-character width)
# Format a string.
puts sprintf("%s scored %d points.", "Alice", 85)
# Alice scored 85 points.
# Pass multiple values using an array.
puts "Name: %s, Age: %d" % ["Bob", 30]
# Name: Bob, Age: 30
# Convert to hexadecimal and binary.
puts sprintf("%x", 255) # ff
puts sprintf("%X", 255) # FF
puts sprintf("%b", 10) # 1010
puts sprintf("0x%08x", 255) # 0x000000ff
# Display a percent sign.
puts sprintf("The tax rate is %d%%.", 10) # The tax rate is 10%.
Notes
Ruby's sprintf (also known as format) uses C-style format specifiers to format numbers and strings into a specific layout. The % operator is syntactic sugar for sprintf, letting you write more concise code.
In modern Ruby, string interpolation ("#{variable}") is the common approach, but sprintf is better suited for zero-padding numbers and controlling decimal precision. When passing multiple values to the % operator, always use an array. A single value without an array ("%s" % variable) is fine, but for multiple values you must write "%s %s" % [value1, value2].
For string padding, you can also use center / ljust / rjust. For type conversion of strings, see to_i / to_f.
If you find any errors or copyright issues, please contact us.