29
12

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のcompact! に注意。

Last updated at Posted at 2019-11-15

経緯

compact!メソッドによって仕事でバグを生み出してしまったので、備忘録としてアウトプット

compact、compact!の戻り値

compactcompact!は配列からnilを弾くが、配列にnilが含まれていない時、compact!の戻り値が予想していないものだった。。。

## arrayがnilを含んでいる時
array = [1,2,3,4,5,nil]

# compact
array.compact
=> [1, 2, 3, 4, 5]

# compact!
array.compact!
=> [1, 2, 3, 4, 5]


## arrayにnilがない時
array = [1,2,3,4,5]

# compact
array.compact
=> [1, 2, 3, 4, 5]

# compact!
array.compact!
=> nil
#ふぁ!?!?

結論

nilを含んでいない配列にcompact!を使うと、「nil含んでねーじゃねーか」的な感じでnilが返ってくるので、注意!!!

29
12
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?