Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number - Prefer annotated tokens (like `%<foo>s`) over unannotated tokens (like `%s`) (Rubocop)

I have this line of code which Rubocop is complaining about

offset = -7
format('%.2i', offset)

Rubocop's message is

rubocop: warning C - Style/FormatStringToken: Prefer annotated tokens (like %<foo>s) over unannotated tokens (like %s).

But even when reading the explanations in the documentation https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/FormatStringToken I cannot make it compliant.

The goal of the code is to add a 0 whenever the offset is a single digit number and to not add anything when the number has two digits already.

I tried the following:

offset = -7
format('%.2{offset}', offset: offset)
like image 513
Clara Avatar asked Apr 16 '20 15:04

Clara


1 Answers

To specify styles, you have to use <offset>, not {offset}. The correct syntax is:

format('%<offset>.2i', offset: offset)
#=> "-07"

The <variable_name> part goes between % and .2i.

like image 140
Stefan Avatar answered Oct 19 '22 05:10

Stefan