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
止まらないで動いたー。