LoginSignup
1
1

More than 5 years have passed since last update.

RuboCop | Style/NonNilCheck

Last updated at Posted at 2014-07-10

RuboCop | Style/NonNilCheck

概要

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

以下のコードを

if !hoge.nil?
if hoge != nil?

以下のコードに変更するように警告します。

if hoge

ただし、デフォルト時は

if hoge != nil?

のみに警告を出します。

設定値一覧

設定対象 設定値 内容 デフォルト
IncludeSemanticChanges false hoge != nil?のようなケースに警告をしない
IncludeSemanticChanges true hoge != nil?のようなケースに警告をする --

NonNilCheck

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

検証プログラム

non_nil_check.rb

def hoge(msg)
  puts msg if !msg.nil?
end

def hige(msg)
  puts msg if msg != nil
end

def hage(msg)
  puts msg if msg
end

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

.rubocop.yml

NonNilCheck:
  IncludeSemanticChanges: false
Style/NegatedIf:
  Enabled: false
$ rubocop non_nil_check.rb
Inspecting 1 file
C

Offenses:

non_nil_check.rb:6:23: C: Explicit non-nil checks are usually redundant.
  puts msg unless msg != nil
                      ^^

1 file inspected, 1 offense detected

実行結果 true に設定します

.rubocop.yml

NonNilCheck:
  IncludeSemanticChanges: true
Style/NegatedIf:
  Enabled: false
$ rubocop non_nil_check.rb
Inspecting 1 file
C

Offenses:

non_nil_check.rb:2:19: C: Explicit non-nil checks are usually redundant.
  puts msg unless !msg.nil?
                  ^^^^^^^^^
non_nil_check.rb:6:23: C: Explicit non-nil checks are usually redundant.
  puts msg unless msg != nil
                      ^^

1 file inspected, 2 offenses detected

補足

この警告は rubocop -a で修正可能です。

RuboCopまとめ記事

1
1
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
1
1