Ruby 2.3.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Arrayクラス > combination
combination(n) {|c| block } -> self
[permalink][rdoc]combination(n) -> Enumerator
サイズ n の組み合わせをすべて生成し、それを引数としてブロックを実行します。
得られる組み合わせの順序は保証されません。ブロックなしで呼び出されると、組み合わせを生成する Enumerator オブジェクトを返します。
a = [1, 2, 3, 4]
a.combination(1).to_a #=> [[1],[2],[3],[4]]
a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
a.combination(4).to_a #=> [[1,2,3,4]]
a.combination(0).to_a #=> [[]]: one combination of length 0
a.combination(5).to_a #=> [] : no combinations of length 5
ブロックが与えられた場合、作成した配列の各要素を引数としてブロックを実行して self を返します。
a = [1, 2, 3, 4]
result = []
a.combination(2) {|e| result << e} # => [1,2,3,4]
result #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
[SEE_ALSO] Array#permutation, Array#repeated_combination