Formatting strings and numbers
format and specifiers
format takes a template and the values, and returns a string. The specifiers are the C ones, so a reader coming from C or Python recognises them at once:
ruby -e 'puts format("%-10s %04d", "Ada", 42)'
Ada 0042
%-10s is a string in ten columns, left aligned; %04d is an integer in four columns padded with zeros. The percent operator does the same with the template on the left:
ruby -e 'puts "%-10s|" % "Ada"'
Ada |
A float takes a precision: %.2f prints two decimals and rounds, which is the line to use for a price or a timing. The % form and format produce the same string; pick one per project.
Width and alignment
For a table, the padding methods read better than a template: rjust and ljust take a width and an optional fill character, and center does both sides:
ruby -e 'puts "Ada".rjust(6, "."); puts "Ada".ljust(6, "."); puts "Ada".center(7, "-")'
...Ada
Ada...
--Ada--
A number pads the same way after to_s, which is the reason a column of numbers lines up only after the conversion.
A report from a heredoc
A multi-line report is a heredoc with interpolation, and the table from the previous section supplies the rows:
rows = [["Ada", 3], ["Bob", 12]] puts <<~REPORT Name Count #{rows.map { |name, count| format("%-10s %3d", name, count) }.join("\n")} REPORT
ruby report.rb
Name Count
Ada 3
Bob 12
<<~ strips the common indentation, so the heredoc can sit inside a method without leading spaces in the output. The inner format keeps the columns straight.
What to watch for
A template with the wrong number of values raises
ArgumentError, and so does a string that is not a
number; an object that cannot be converted at all raises
TypeError. All of them are better than a silently
shifted table, and they name the line.
Widths are characters, not display columns: a string with an emoji or a
wide character takes more terminal space than its length says. For a
table that must align, keep the cells to plain ASCII or accept the
wobble.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
format("%-10s %04d", "Ada", 42)print?Answer
Ada 0042
The name fills ten columns on the left and the number four on the right, padded with zeros.
-
What does
%04dmean?Answer
An integer in four columns, padded with zeros
The 0 flag pads with zeros up to the width of 4.
-
What does this program print?
puts "%-10s|" % "Ada"Answer
Ada |
%-10s pads the name to ten columns on the right, so the bar comes after six spaces.
-
Which method pads a string on the left?
Answer
rjust
rjust puts the fill characters on the left, so the text ends at the right edge.
-
What does
"Ada".center(7, "-")return?Answer
--Ada--
center pads both sides; the odd column goes to the right.
-
Which specifier prints a price with two decimals?
Answer
%.2f
The dot introduces the precision, and f is the float conversion.
-
What does
format("%d %d", 1)raise?Answer
ArgumentError: too few arguments
The template wants two values and the call gives one.
-
What does
format("%d", "x")raise?Answer
ArgumentError: invalid value for Integer
The string is not a number, so the conversion reports ArgumentError.
-
What does this program print?
rows = [["Ada", 3], ["Bob", 12]] rows.each { |name, count| puts format("%-10s %3d", name, count) }Answer
Ada 3 / Bob 12
The name fills ten columns, then a space, then the count in three columns.
-
Why does a column of numbers line up only after
to_s?Answer
Because padding is a string method, and a number must become a string first
rjust and ljust pad strings, so the number is converted before the padding.
Article author: Arthur Isaev