sprintf() / % Operator
| Since: | Ruby 1.8(2003) |
|---|
A function and method for generating formatted strings. Commonly used for zero-padding numbers and controlling decimal places.
Syntax
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
sample_sprintf_percent.rb
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 score: %d.", "user_1", 220)
# user_1 score: 220.
# Pass multiple values using an array.
puts "Name: %s, Role: %s" % ["user_2", "editor"]
# Name: user_2, Role: editor
# 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%.
Running the above produces the following output:
ruby sprintf_percent.rb
42
00042
+42
00042
3.14
3.14
user_1 score: 220.
Name: user_2, Role: editor
ff
FF
1010
0x000000ff
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.