Ruby String Formatting
Interpolation ("#{x}") handles most everyday string building. When you need precise control — two decimal places, padded columns, leading zeros, thousands separators — reach for format strings.
format / sprintf
format (and its twin sprintf) takes a template with % placeholders and fills them in:
puts format("%s scored %d points", "Ria", 87)
puts format("Price: %.2f", 4.5)
puts format("%05d", 42)
puts format("%x / %o / %b", 255, 8, 5)
puts format("%e", 123456.789)
puts format("100%% done")Ria scored 87 points
Price: 4.50
00042
ff / 10 / 101
1.234568e+05
100% done
| Placeholder | Meaning | Example | Result |
|---|---|---|---|
%s |
string (to_s) |
format("%s", :ok) |
ok |
%p |
inspect | format("%p", "ok") |
"ok" |
%d |
integer | format("%d", 7.9) |
7 |
%f |
float | format("%.1f", 2.25) |
2.2 |
%e |
scientific | format("%.1e", 1500) |
1.5e+03 |
%x %o %b |
hex, octal, binary | format("%b", 6) |
110 |
%% |
a literal % |
format("50%%") |
50% |
Width, alignment and padding
A number between % and the letter sets the minimum width. A - aligns left; a 0 pads numbers with zeros; + always shows the sign:
puts format("[%8s]", "right")
puts format("[%-8s]", "left")
puts format("[%8.2f]", 3.14159)
puts format("[%-8d]", 42)
puts format("[%08.3f]", 3.14159)
puts format("[%+d] [%+d]", 5, -5)[ right]
[left ]
[ 3.14]
[42 ]
[0003.142]
[+5] [-5]
Building a table
Width specifiers make neat text tables:
items = [["Notebook", 3, 2.5], ["Fountain pen", 1, 24.0], ["Ink", 2, 6.75]]
puts format("%-14s %4s %9s", "Item", "Qty", "Total")
puts "-" * 29
items.each do |name, qty, price|
puts format("%-14s %4d %9.2f", name, qty, qty * price)
end
puts "-" * 29
grand = items.sum { |_, q, p| q * p }
puts format("%-14s %14.2f", "Grand total", grand)Item Qty Total
-----------------------------
Notebook 3 7.50
Fountain pen 1 24.00
Ink 2 13.50
-----------------------------
Grand total 45.00
The % operator
"template" % values is a short form of format. Pass an array for several values:
puts "%.1f%%" % 45.678
puts "%s-%03d" % ["INV", 7]
puts "%-6s|" % "ab"45.7%
INV-007
ab |
Named placeholders
With a hash, refer to values by name. %{name} inserts the value as-is, %<name>f applies a format:
data = {city: "Quito", temp: 18.456, rain: 0.8}
puts format("%{city}: %<temp>.1f°C, rain %<rain>d%%", data)
puts "Hello %{who}!" % {who: "world"}Quito: 18.5°C, rain 0%
Hello world!
Number formatting helpers
Some formatting jobs are easier with plain methods:
p 3.14159.round(2)
p 7.to_s.rjust(3, "0")
p 1234567.to_s.reverse.scan(/\d{1,3}/).join(",").reverse
p 1234567.89.floor.digits.each_slice(3).map(&:join).join(",").reverse
p 0.256.round(3) * 100
p (0.256 * 100).round(1).to_s + "%"
p 255.to_s(16).upcase3.14
"007"
"1,234,567"
"1,234,567"
25.6
"25.6%"
"FF"
Ruby's core has no built-in thousands separator; the regex trick above (reverse, group by three, join, reverse back) is a common idiom. Rails adds helpers such as number_with_delimiter for this.
Interpolation with formatting
You can call format inside an interpolation, or use round/ljust directly:
name = "Kofi"
balance = 1520.5
puts "#{name.ljust(8, '.')}#{format('%10.2f', balance)}"
puts "Balance: #{'%.2f' % balance} USD"Kofi.... 1520.50
Balance: 1520.50 USD
Which tool when?
| Need | Use |
|---|---|
| Insert values into text | "Hi #{name}" |
| Fixed decimals | format("%.2f", x) or x.round(2) |
| Leading zeros | format("%03d", n) or n.to_s.rjust(3, "0") |
| Aligned columns | format("%-10s %5d", ...) or ljust/rjust |
| Reusable template with names | format("%{a} %{b}", a:, b:) |
Note:
round(2)returns a number, so2.5.round(2)prints as2.5, not2.50. When you need the trailing zero for display, useformat("%.2f", x).
Test yourself
What does format("%.2f", 3.14159) return?
- "3.14159"
- "3.14"
- "3.1"
- 3.14
What does format("%04d", 7) return?
- "7000"
- "0007"
- " 7"
- "7 "
How do you print a literal percent sign inside a format string?
\%%%%p#%