The Ruby Craftsman
Array Permutation
When invoked with a block, yield all permutations of length n of the elements of the array, then return the array itself.
If n is not specified, yield all permutations of all elements.
The implementation makes no guarantees about the order in which the permutations are yielded.
If no block is given, an Enumerator is returned instead.
Examples:
I have had a few times where I wanted to test something where I need all combination of items. Thinking of those combination by your self can be cumbersome.
Here is contrived example where we have #add
that takes two arguments. Since permutation will return an Enumerator we can each through the permutations. This lazy operation is helpful because to calculate all of these permutations before hand is time consuming and if the exception fails on the first iteration or somewhere in the middle that is known right way instead of waiting for all permutations to be calculated and then getting failures.
Note that I am using *p
, called splat, makes the array items into arguments for the method. Also p.inject(&:*)
, called symbol to proc, will call *
on each element in the array by the sum of that last iteration.