9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RuboCop | Style/FormatString

Last updated at Posted at 2014-07-02

RuboCop | Style/FormatString

概要

RuboCopの「Style/FormatString」警告について。

Rubyでは書式付き文字列の作成方法が複数あり、
どれを利用するか設定し、統一されているかチェックすることができます。

設定値一覧

設定対象 設定値 内容 デフォルト
EnforcedStyle format formatを利用する
EnforcedStyle sprintf sprintfを利用する --
EnforcedStyle percent %記法を利用する --

FormatString

各設定値での検証結果をまとめます。

検証プログラム

format_string.rb

hoge = "hoge"
puts format("%10s", hoge)
puts sprintf("%10s", hoge)
puts "%10s" % hoge

実行結果 デフォルト の場合

.rubocop.yml

※明示的に設定しているが、デフォルト値なので何も設定しなくてもよい

FormatString:
  EnforcedStyle: format
$ rubocop format_string.rb
Inspecting 1 file
C

Offenses:

format_string.rb:3:6: C: Favor format over sprintf.
puts sprintf('%10s', hoge)
     ^^^^^^^
format_string.rb:4:13: C: Favor format over String#%.
puts '%10s' % hoge
            ^

1 file inspected, 2 offenses detected

実行結果 sprintf の場合

.rubocop.yml

FormatString:
  EnforcedStyle: sprintf
$ rubocop format_string.rb
Inspecting 1 file
C

Offenses:

format_string.rb:2:6: C: Favor sprintf over format.
puts format('%10s', hoge)
     ^^^^^^
format_string.rb:4:13: C: Favor sprintf over String#%.
puts '%10s' % hoge
            ^

1 file inspected, 2 offenses detected

実行結果 percent の場合

.rubocop.yml

FormatString:
  EnforcedStyle: percent
$ rubocop format_string.rb
Inspecting 1 file
C

Offenses:

format_string.rb:2:6: C: Favor String#% over format.
puts format('%10s', hoge)
     ^^^^^^
format_string.rb:3:6: C: Favor String#% over sprintf.
puts sprintf('%10s', hoge)
     ^^^^^^^

1 file inspected, 2 offenses detected
9
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?