Home / Reference / Kernel Methods / Kernel#sprintf Kernel#sprintf skernel-printf(format_string, *args) -> string Returns String · Updated May 16, 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
Parameter Type Default Description format_stringString— The format string containing literal text and format specifiers *argsObject— Values to be formatted, one per format specifier
Specifier Type Description %sString Formats the argument as a string %d or %iInteger Formats the argument as a decimal integer %fFloat Formats the argument as a floating-point number %xInteger Formats as hexadecimal %oInteger Formats as octal %bInteger Formats as binary %%— Literal percent sign
Examples
name = "Alice"
age = 30
skernel - printf ( "Name: %s, Age: %d" , name, age)
# => "Name: Alice, Age: 30"
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"
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
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
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"
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