0
1

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】配列を条件に基づいて分割したい

Last updated at Posted at 2021-06-20

概要

Enumerable#partitionメソッド使って、条件に当てはまるものとそうでないものに分類できます。
結果が真(true)の組みと偽(true以外)の組みの2つの要素からなる配列を返します。

array = [1,2,3,6,7,8]
array_partition = array.partition {|i| i < 5}
array_partition #=> [[1, 2, 3], [6, 7, 8]]
array_partition[0] #=> [1, 2, 3]
array_partition[1] #=> [6, 7, 8]

どんな時に使うと便利?

数値などでpartitionメソッドを使って分割すると、真(true)の組みと偽(true以外)の組みに分割した配列を作成できて便利に使用できます。

例:3で割り切れる数値の配列とそうでない配列に分割

array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
array_partition = array.partition {|i| i % 3 == 0 }

array_partition #=> [[9, 6, 3, 0], [10, 8, 7, 5, 4, 2, 1]]
# 3で割り切れる数値の配列
array_partition[0] #=> [9, 6, 3, 0] 
# 3で割り切れない数値の配列
array_partition[1] #=> [10, 8, 7, 5, 4, 2, 1]

参考資料

Ruby 3.0.0 リファレンスマニュアルEnumerable#partition

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?