0
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 3 years have passed since last update.

[Ruby] compactメソッド

Posted at

##はじめに
オリジナルアプリの改修をしてまして、アルゴリズムを組んでいたら、とても便利なメソッドを見つけましたので記事にしておきます。

##compactメソッド
compactメソッドは配列に含まれるnilを取り除いてくれるものです。

array = [1, 2, 3, 4, 5, nil, 6]
except_nil = array.compact

=> [1, 2, 3, 4, 5, 6]

私の場合each文でデータベースから値を探して、配列に放り込んでいたときにnilが入ってきたのでcompactを使用しました。

!をつければ破壊的な使い方もできるようです。

array = [1, 2, 3, 4, 5, nil, 6]
array.compact!

=> [1, 2, 3, 4, 5, 6]

arrayの中身そのものを書き換えちゃうのですね。

0
0
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
0
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?