12
7

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.

Rubyでinclude?メソッドを使った時によく出る'undefined method `include?' for nil:NilClass'エラーの対処法

Posted at

include?メソッドはよく使うが、僕みたいな初心者が使うと良く'undefined method `include?' for nil:NilClass'エラーが出る。

hoge.rb
array = ["hoge", "hogehoge", "hogehogehoge", nil]
array.each do |ary|
 p ary.include?("hoge")
end

#=> true
#=> true
#=> true
#=> NoMethodError: undefined method `include?' for nil:NilClass

こんな感じ。これで良く処理が止まっちゃう。
こう書くと便利。

hoge.rb
require 'active_support/core_ext/object/try'

array = ["hoge", "hogehoge", "hogehogehoge", nil]
array.each do |ary|
 p ary.try(:include?, "hoge")
end

#=> true
#=> true
#=> true
#=> nil

止まらないで動いたー。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?