How to force Ruby string variable output using puts
to n characters so that if the variable is longer, it will be truncated, if shorter, it will be expanded by trailing or leading spaces?
Is there some standard method to do this?
Ruby supports using format strings, like many other languages:
[11] (pry) main: 0> '%3.3s' % 'f' => " f" [12] (pry) main: 0> '%3.3s' % 'foo' => "foo" [13] (pry) main: 0> '%3.3s' % 'foobar' => "foo"
If you want to pad on the right, use a -
in the format string:
[14] (pry) main: 0> '%-3.3s' % 'f' => "f " [15] (pry) main: 0> '%-3.3s' % 'foo' => "foo" [16] (pry) main: 0> '%-3.3s' % 'foobar' => "foo"
You could also use printf
or sprintf
, but I prefer the more generic %
, which is like sprintf
.
From the sprintf
docs:
s | Argument is a string to be substituted. If the format | sequence contains a precision, at most that many characters | will be copied.
and:
- | all | Left-justify the result of this conversion.
What if I want to pad not with spaces but with some other character?
The underlying Ruby code is written in C, and it's hard-coded to use ' '
as the pad character, so that's not possible directly, unless you want to modify the source, recompile your Ruby, and live with a one-off version of the language. Instead, you can do something like:
[17] (pry) main: 0> ('%-3.3s' % 'f').gsub(' ', '.') => "f.."
This gets a lot more complicated than a simple gsub
though. Often it's better to adjust the string without using format strings if you need to supply special characters. Format strings are very powerful but they're not totally flexible.
Otherwise, I'd go with something like @steenslag's solution, which is the basis for rolling your own. You lose the ability to use format strings and have to rely on concatenating your strings or something similar to get columnar output, but it will also work.