4
5

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

Posted at

RuboCop | Style/TrailingComma

概要

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

配列やハッシュの末尾のカンマの有無をチェックします。
デフォルトではカンマがあると警告が出ます。

しかし、コピペやコード生成のことを考えると最後の行にも
カンマがある方が便利だったりするので用途や考え方によって
設定値を変更すると良さそうです。

TrailingComma

設定値一覧

設定対象 対象 内容 デフォルト
EnforcedStyle comma 最後の要素にカンマを必要とする --
EnforcedStyle no_comma 最後の要素にカンマを必要としない

検証プログラム

trailing_comma.rb
print [
  1,
  2,
  3,
]
h1 = {
  key1: :value1,
  key2: :value2,
}
print h1
print [
  1,
  2,
  3
]
h2 = {
  key1: :value1,
  key2: :value2
}
print h2

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

.rubocop.yml
TrailingComma:
  EnforcedStyleForMultiline: no_comma
$rubocop trailing_comma.rb
Inspecting 1 file
C

Offenses:

trailing_comma.rb:4:4: C: Avoid comma after the last item of an array.
  3,
   ^
trailing_comma.rb:8:16: C: Avoid comma after the last item of a hash.
  key2: :value2,
               ^

1 file inspected, 2 offenses detected

実行結果 final_blank_line に設定した場合

.rubocop.yml
TrailingComma:
  EnforcedStyleForMultiline: comma
$ rubocop trailing_comma.rb
Inspecting 1 file
C

Offenses:

trailing_comma.rb:14:3: C: Put a comma after the last item of a multiline array.
  3
  ^
trailing_comma.rb:18:3: C: Put a comma after the last item of a multiline hash.
  key2: :value2
  ^^^^^^^^^^^^^

1 file inspected, 2 offenses detected

対象コード

https://github.com/bbatsov/rubocop/blob/master/lib/rubocop/cop/style/trailing_comma.rb
https://github.com/bbatsov/rubocop/blob/master/spec/rubocop/cop/style/trailing_comma_spec.rb

RuboCopまとめ記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?