Edited at

Ruby Arrayの組み合わせ系メソッドまとめ

More than 1 year has passed since last update.

覚えていると便利なArrayの組み合わせ系メソッドのまとめです。

(一部ActiveSupportのメソッドもあります)


combination

組み合わせ(順序なし、重複を許さない)

# to_a

> [1,2,3].combination(2).to_a
=> [[1, 2], [1, 3], [2, 3]]

# map
> [1,2,3].combination(2).map {|arr| arr.map(&:to_s) }
=> [["1", "2"], ["1", "3"], ["2", "3"]]


repeated_combination

組み合わせ(順序なし、重複を許す)

> [1,2,3].repeated_combination(2).to_a

=> [[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]


permutation

順列(順序あり、重複を許さない)

> [1,2,3].permutation(2).to_a

=> [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]


repeated_permutation

重複順列(順序あり、重複を許す)

> [1,2,3].repeated_permutation(2).to_a

=> [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]


product

複数の配列の要素の組み合わせ

配列の配列を作成して返す。

[1,2].product([3,4], [5,6])

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


zip

複数の配列の要素の組み合わせ

配列の配列を作成して返す。

> [1,2,6,7].zip([3,4,5])

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


transpose

行列を入れ替える

> [[1,2,6], [3,4,5]].transpose

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


( * )

5.times.map { [0] * 3 }

=> [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]


in_groups_of (ActiveSupport)

指定個数毎に切り分ける

[1, 2, 3, 4, 5, 6, 7].in_groups_of(2, false)

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


in_groups (ActiveSupport)

指定個数に切り分ける

[1,2,3,4,5,6,7].in_groups(2, false)

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