Ruby’s format Method
To format a String in Ruby we can use the
Kernel#sprintf method. They work by returning a copy of the String passed in, with its format sequence replaced by the additional arguments passed to it. This is easier with an example:
sprintf('%d %d', 20, 10) # => "20 10"
The first argument passed in method
sprintf is a String object containing two format sequences.
A format sequence is a parcent sign followed by flags, width and precision indicators, then terminated with a field type character.
In the example above, the
%d is the field type character. It converts the passed argument as a decimal number.
[width] controls the size of the returned String object, while
[.precision] mainly specify the number of digits after the decimal points.
A common use for
sprintf is to format the result of Float objects.
format('%f', 1.0/3.0) # => "0.333333" format('%.2f', 1.0/3.0) # => "0.33"
Note the use of the dot
. before the precision number.
Rubocop advises against using the
Prefer the use of
sprintfand its alias
formatover the fairly cryptic
The documentation does not give any reason why.
String#% basically do the same thing. However,
String#% is an instance method of the String class, while the former is a command.
On his blog, Rubocop’s author gives several answer:
One reason to prefer the Kernel methods over the String method is the inconsistencies of the
% method which takes either a single element or an array of elements. Another reason is its cryptic meaning:
% can either be a modulo or the
String#% method, which, without context is hard to parse:
a % b
Even with hardcoded values, the repetition of the
% symbol is difficult to parse:
'%d %d' % [20, 10] # => "20 10"