10
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/GuardClause

Posted at

RuboCop | Style/GuardClause

概要

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

ガード節の使用をチェックします。
デフォルトでは condition 内の処理が 1 行以上の場合にチェックします。

GuardClause

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

検証プログラム

guard_clause.rb

def test
  if something
    a = 1
    print a
    work
  end
end

def test
  return unless something
  a = 1
  print a
  work
end

def test
  a = 1
  print a
  work if something
end

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

.rubocop.yml

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

GuardClause:
  MinBodyLength: 1

IfUnlessModifier:
  Enabled: false
$ rubocop guard_clause.rb
Inspecting 1 file
C

Offenses:

guard_clause.rb:2:3: C: Use a guard clause instead of wrapping the code inside a conditional expression.
  if something
  ^^

1 file inspected, 1 offense detected

実行結果 4行以上 の場合にチェックするように設定します

.rubocop.yml

GuardClause:
  MinBodyLength: 4

IfUnlessModifier:
  Enabled: false
$ rubocop guard_clause.rb
Inspecting 1 file
.

1 file inspected, no offenses detected
10
9
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
10
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?