4
3

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/SingleLineBlockParams

Posted at

RuboCop | Style/SingleLineBlockParams

概要

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

reduce, injectなど1行でブロック呼び出しした場合の変数名の命名規則をチェックする。
デフォルトでは reduce ( inject ) のみ定義されていて、変数名は ( a , e ) に設定されている。

SingleLineBlockParams

設定値一覧

設定対象 対象 内容 デフォルト
Methods reduce reduceメソッドを1行で書いた場合の引き数名 a, e
Methods inject injectメソッドを1行で書いた場合の引き数名 a, e

検証プログラム

signal_exception.rb
print [*1..5].reduce { |a, e|a += e; a }
print [*1..5].inject { |a, e|a += e; a }
print [*1..5].reduce { |a, v|a += v; a }
print [*1..5].inject { |sum, e|sum += e; sum }
print [*1..5].map { |e|e * 2 }

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

※CollectionMethods/Semicolon/EndOfLine/EachWithObjectは
サンプルの都合上、余計な警告が出ないようにするための設定です。

.rubocop.yml
SingleLineBlockParams:
  Methods:
    - reduce:
        - a
        - e
    - inject:
        - a
        - e

CollectionMethods:
  Enabled: false

Semicolon:
  Enabled: false

EndOfLine:
  Enabled: false

EachWithObject:
  Enabled: false
$ rubocop semicolon.rb
Inspecting 1 file
C

Offenses:

semicolon.rb:1:13: C: Do not use semicolons to terminate expressions.
msg = 'hoge'; print msg
            ^

1 file inspected, 1 offense detected

実行結果 mapに関する設定も追加します

※CollectionMethods/Semicolon/EndOfLine/EachWithObjectは
サンプルの都合上、余計な警告が出ないようにするための設定です。

.rubocop.yml
SingleLineBlockParams:
  Methods:
    - reduce:
        - a
        - e
    - inject:
        - a
        - e
    - map:
        - rubocop_saiko

CollectionMethods:
  Enabled: false

Semicolon:
  Enabled: false

EndOfLine:
  Enabled: false

EachWithObject:
  Enabled: false
$ rubocop single_line_block_params.rb
Inspecting 1 file
C

Offenses:

single_line_block_params.rb:3:24: C: Name reduce block params |a, e|.
print [*1..5].reduce { |a, v|a += v; a }
                       ^^^^^^
single_line_block_params.rb:4:24: C: Name inject block params |a, e|.
print [*1..5].inject { |sum, e|sum += e; sum }
                       ^^^^^^^^
single_line_block_params.rb:5:21: C: Name map block params |rubocop_saiko|.
print [*1..5].map { |e|e * 2 }
                    ^^^

1 file inspected, 3 offenses detected

RuboCopまとめ記事

4
3
0

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?