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