Ruby has several methods for formatting strings according to what is called format specification.
#All"hoge = 1 + 2"Is evaluated as
sprintf('hoge = %s + %s', 1, 2)
format('hoge = %s + %s', 1, 2)
'hoge = %s + %s' % [1, 2]
Both format
and sprintf
are Kernel methods and are aliases with different names.
https://docs.ruby-lang.org/ja/latest/method/Kernel/m/format.html
The third String #%
has a slightly different coat color, but it seems that you can do virtually the same thing just by calling format
by regarding the self side as a format-specified character string.
https://docs.ruby-lang.org/ja/latest/method/String/i/=25.html
At the time of this article, the default behavior of RuboCop is "Allow only format methods". I will be corrected.
hoge.rb:3:18: C: Style/FormatString: Favor format over String#%.
'hoge = %s + %s' % [1, 2]
^
In addition, the traditional style like % s
is angry that it is not recommended.
hoge.rb:1:16: C: Style/FormatStringToken: Prefer annotated tokens (like %<foo>s) over unannotated tokens (like %s).
format('hoge = %s + %s', 1, 2)
^^
It seems that it is recommended to add annotation _ \ <name > _ to the format specification and pass the value you want to fit in Hash.
format('hoge = %<x>d + %<y>d', x: 1, y: 2)
By the way, there is also _% {name} _ in a similar notation, but it seems that it is not recommended. You should specify the specifier.
hoge.rb:4:16: C: Style/FormatStringToken: Prefer annotated tokens (like %<foo>s) over template tokens (like %{foo}).
format('hoge = %{x} + %{y}', x: 1, y: 2)
^^^^
RuboCop seems to be intended to unify the style to one, with a default of format
.
https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/FormatString
The original issue seems to be ↓, but it seems to be a rough process like "Isn't it nice to have it?" Or "Like!" Rather than being decided after a difficult discussion. Maybe default is more than a matter of decision?
Cop idea: Enforce preferred style for format string sequences #3438 https://github.com/rubocop-hq/rubocop/issues/3438
The claim that _% \ <name > _ is better than _% {name} _ seems to be based on The Ruby Style Guide.
When using named format string tokens, favor %
s over %{name} because it encodes information about the type of the value. https://rubystyle.guide/#named-format-tokens
In Ruby, so-called printf-like string formatting methods are provided in several styles.
If you use Ruby for modern, especially team development, you will often want to introduce RuboCop. Here is a brief summary of what styles are specified and what the rationale is.
Recommended Posts