[Ruby] Use named format with Ruby’s format method

2 minute read

Ruby has several methods that format strings according to what is called a format specification.

  • RuboCop got angry when I wrote these, so I summarized the process.
# All evaluate to "hoge = 1 + 2"
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 just aliases. https://docs.ruby-lang.org/ja/latest/method/Kernel/m/format.html

The third String#% is a little different in color, but it seems that the same thing can be done by just calling format by regarding the self side as a character string of the format specification. https://docs.ruby-lang.org/ja/latest/method/String/i/=25.html

At the time of writing this article, the default behavior of RuboCop is “allow format methods only”. You will be corrected.

hoge.rb:3:18: C: Style/FormatString: Favor format over String#%.
'hoge = %s + %s' %[1, 2]
                 ^

In addition, it makes people angry that traditional %s styles are 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)
               ^^

How to write after all

Annotation <name> is added to the format specification, and the value to be embedded seems to be recommended to be passed in Hash.

format('hoge = %<x>d + %<y>d', x: 1, y: 2)

By the way, there is a similar notation %{name}, but it seems not recommended. It means that the specifier should be specified.

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 styles, default is format. https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/FormatString

The underlying issue seems to be ↓, but rather than being decided after an esoteric discussion, it seems that it is a rough process such as “I hope it exists” “Like”. Perhaps 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

Summary

Ruby provides so-called printf-like string formatting methods in several styles.

If you use Ruby in a modern way, especially in team development, you will probably introduce RuboCop. I briefly summarized what style was specified at that time and what kind of basis it was based on.

Tags:

Updated: