2
0

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.

Array#inject でNoMethodError: ... for nil:NilClass

Last updated at Posted at 2018-05-19

Array#inject に渡すブロックは、Arrayのどの要素を与えられても値を返す必要がある。

そのことを忘れると、memoの値が nilになるエラーに出くわす。

失敗の例

配列内の、3より小さな要素の数を数えたい

pry(main)> a = [2,5,1,3,4]
pry(main)> a.inject(0) { |count, num| count + 1 if num < 3 }
NoMethodError: undefined method `+' for nil:NilClass
from (pry):2:in `block in __pry__'

修正例

pry(main)> a = [2,5,1,3,4]
pry(main)> a.inject(0) { |count, num| num < 3 ? count + 1 : count }
=> 2

# コメントで教えていただきました。この例の場合、injectではなくcountを使うことができます。

a.count { |num| num < 3 }
=> 2
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?