74
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

# Ruby 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]]
``````
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away