Kernel#sprintf
skernel-printf(format_string, *args) -> string skernel-printf (also available as Kernel.format) formats values according to a format string. It’s identical to kernel-printf but returns the result as a string instead of printing it.
That separation is helpful when you want to prepare formatted text first and decide later where it should go. The method keeps the layout rules in the format string, which makes the result easier to read and reuse.
Key takeaways
sprintfreturns a formatted string, so you can store or transform the result before printing it.- Keep the format string close to the data so the output shape stays easy to inspect.
- Use width, precision, and alignment specifiers when you want predictable presentation.
- Reach for
sprintfwhen you need a small formatting helper without side effects. - Pair it with
printfwhen you want the same formatting rules but direct output instead of a return value.
Syntax
skernel-printf(format_string, *args)
# or
format(format_string, *args)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
format_string | String | — | The format string containing literal text and format specifiers |
*args | Object | — | Values to be formatted, one per format specifier |
Format specifiers
| Specifier | Type | Description |
|---|---|---|
%s | String | Formats the argument as a string |
%d or %i | Integer | Formats the argument as a decimal integer |
%f | Float | Formats the argument as a floating-point number |
%x | Integer | Formats as hexadecimal |
%o | Integer | Formats as octal |
%b | Integer | Formats as binary |
%% | — | Literal percent sign |
Examples
Basic string formatting
name = "Alice"
age = 30
skernel-printf("Name: %s, Age: %d", name, age)
# => "Name: Alice, Age: 30"
Floating-point formatting extends sprintf’s type system beyond integers. The %f specifier accepts a precision modifier between the percent sign and the type letter — %.2f means “two digits after the decimal.” This is what you reach for when dollar amounts, percentages, or scientific measurements need a consistent number of decimal places no matter what value comes in.
Floating-point formatting
price = 19.99
tax = 0.08
skernel-printf("Price with tax: $%.2f", price * (1 + tax))
# => "Price with tax: $21.59"
skernel-printf("Pi to 3 decimals: %.3f", Math::PI)
# => "Pi to 3 decimals: 3.142"
When output needs to line up in columns, width and alignment specifiers do the work. A number between % and the type letter sets the minimum field width, and the - flag left-justifies the content within that space. Zero-padding with 0 is especially common for IDs and codes that should always appear at a fixed width, like invoice numbers or zip codes.
Number formatting with padding
skernel-printf("%05d", 42) # => "00042" (zero-padded to 5 digits)
skernel-printf("%-10s", "hello") # => "hello " (left-justified)
skernel-printf("%+d", 42) # => "+42" (always show sign)
Beyond decimal presentation, sprintf can convert integers into hexadecimal, octal, and binary representations. The %x formatter turns a number into its base-16 equivalent, and adding the # flag prepends the customary 0x prefix that signals a hex literal in Ruby and many other languages. Binary output via %b is useful when you need to inspect bit flags or display bitmask values in logs.
Hexadecimal and binary
skernel-printf("Hex: %x", 255) # => "Hex: ff"
skernel-printf("Hex: %#x", 255) # => "Hex: 0xff" (with 0x prefix)
skernel-printf("Binary: %b", 42) # => "Binary: 101010"
Formatting a single value is straightforward; the real power of sprintf shows up when you build multi-line layouts. The same width and alignment specifiers that center one value can control an entire table, keeping columns aligned regardless of how long the data in each cell happens to be.
Common patterns
Building formatted tables
headers = %w[Name Score]
rows = [["Alice", 95], ["Bob", 87], ["Carol", 92]]
header = skernel-printf("%-10s %s", *headers)
separator = "-" * 15
puts header
puts separator
rows.each { |row| puts skernel-printf("%-10s %d", *row) }
Running that table-building code prints cleanly aligned columns: the %-10s specifier reserves ten characters for the name column and left-justifies the text, while %d right-aligns the numeric score. The separator line of dashes sits between the header and the data rows, using - repeated fifteen times to span the full width of both columns.
Name Score
---------------
Alice 95
Bob 87
Carol 92
Common formatting tasks deserve their own small helpers. Wrapping sprintf in a method like format_currency gives the formatting logic a clear name and a single place to live. When the currency formatting rule changes — say you need to display negative amounts in parentheses — you change it in one method instead of hunting through the codebase.
Currency formatting
def format_currency(amount)
skernel-printf("$%.2f", amount)
end
format_currency(99) # => "$99.00"
format_currency(9.9) # => "$9.90"
format_currency(1234.56) # => "$1234.56"
Percentage values follow a similar pattern: multiply by 100 and tack on a percent sign. The %% sequence in the format string produces a literal % character, since a lone percent sign starts a format specifier. Keeping the multiplication inside the helper means callers pass a decimal fraction and get a display-ready string without worrying about the arithmetic.
Percentage formatting
def format_percentage(value)
skernel-printf("%.1f%%", value * 100)
end
format_percentage(0.456) # => "45.6%"
format_percentage(1.0) # => "100.0%"
Errors
- ArgumentError: Too few arguments for the format string
- ArgumentError: Invalid format specifier
- Encoding::CompatibilityError: Encoding incompatibility between format string and arguments
Formatting without printing
sprintf is the method to reach for when you want a formatted string but do not want to send it straight to standard output. That makes it a good fit for building messages, table rows, and reusable labels that will be stored or passed somewhere else. The format string still carries the structure, so the reader can see the shape of the final text before the values are filled in. It keeps formatting work separate from printing work.
That separation is useful in code that builds a value now and displays it later. The method can shape numbers, align columns, or add fixed text while still leaving the result as a normal string. Because the formatted text comes back as a value, it can be saved, tested, or combined with other strings before anyone prints it. That makes sprintf a small but practical tool for data that needs a clear final shape.
When to use sprintf
Use sprintf when the output format matters more than the act of printing. It is especially handy for reports, labels, filenames, and log messages where the text needs to look the same every time. If the formatting logic starts to repeat in several places, moving it into a helper method usually keeps the code easier to maintain.
It is also a good fit when you want to compare output in tests. Since sprintf returns a string, you can assert against the exact result without capturing standard output. That makes it a clean choice for code that builds data in one place and consumes it in another.
Common mistakes
One common mistake is mixing up sprintf and printf. The two methods use the same formatting rules, but sprintf returns a string and printf writes to an output stream. If you need to save the result or pass it to another method, sprintf is the better choice.
Another mistake is letting the format string get so clever that the meaning becomes hard to read. The method is most useful when the layout is obvious at a glance. If the format specifiers start to overwhelm the code, a small helper or a dedicated formatter object may be clearer.
Conclusion
sprintf gives you a compact way to build formatted strings without printing them immediately. That makes it useful for reports, labels, and any other text where the final shape matters. Keep the format string nearby, keep the specifiers simple, and let the return value flow into the rest of your code.
See Also
- kernel-printf — prints the formatted string instead of returning it
- Kernel#format — alias for skernel-printf