Rubocop: why not using interpolation in Style::FormatString

Created on 30 Jun 2017  路  6Comments  路  Source: rubocop-hq/rubocop

Currently Style/FormatString cop will complain about things like:

key = '%s/%s' % [dproject, dp.name]

and the autocorrect will change it by:

key = format('%s/%s', dproject, dp.name)

I wonder why not changing it by (using interpolation):

key = "#{dproject}/#{dp.name}"

I find it way more readable. Not sure if can be always be used. :thinking:

RuboCop version

$ rubocop -V
0.49.1 (using Parser 2.4.0.0, running on ruby 2.4.1 x86_64-linux-gnu)
question

Most helpful comment

I was thinking the particular case presented here might be nice to handle: format strings containing only %s references could be replaced with interpolation. Yet another cop, or maybe not worth it 馃

All 6 comments

They are not directly interchangeable. 馃檪 Kernel#format does a lot more. It can pad strings, convert between types, and format numbers, depending on which references you use in the template.

There is a way to make it a bit more readable, and we've discussed adding a cop for it. You can name the references like so:

format("%<foo>s %<bar>s!", foo: "Hello", bar: "world")
#=> "Hello world!"

This cop isn't implemented yet, however.

I was thinking the particular case presented here might be nice to handle: format strings containing only %s references could be replaced with interpolation. Yet another cop, or maybe not worth it 馃

@mikegee

format strings containing only %s references could be replaced with interpolation

Another cop would be great! Documenting that string interpolation is prefer in this case in Style::FormatString would also be a good idea :+1:

There is a way to make it a bit more readable, and we've discussed adding a cop for it. You can name the references like so

Are you referring to something besides what Style/FormatStringToken does?

@backus: Ah! I remember this being mentioned, but didn't realize it was actually added. 馃槏

Is this still an issue?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ana06 picture Ana06  路  3Comments

bbatsov picture bbatsov  路  3Comments

deivid-rodriguez picture deivid-rodriguez  路  3Comments

lepieru picture lepieru  路  3Comments

Aqualon picture Aqualon  路  3Comments