Kernel#sprintf

skernel-printf(format_string, *args) -> string
Returns: String · Updated March 13, 2026 · Kernel Methods
formatting strings kernel

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.

Syntax

skernel-printf(format_string, *args)
# or
format(format_string, *args)

Parameters

ParameterTypeDefaultDescription
format_stringStringThe format string containing literal text and format specifiers
*argsObjectValues to be formatted, one per format specifier

Format Specifiers

SpecifierTypeDescription
%sStringFormats the argument as a string
%d or %iIntegerFormats the argument as a decimal integer
%fFloatFormats the argument as a floating-point number
%xIntegerFormats as hexadecimal
%oIntegerFormats as octal
%bIntegerFormats 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

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"

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)

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"

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) }
Name       Score
---------------
Alice      95
Bob        87
Carol      92

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 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

See Also