Ka Mok Ka Mok - 4 months ago 20
Ruby Question

How to get the permutation of an array without changing the order of its values?

For this array:

a = [8, 2, 22, 97, 38, 15]
, how can I get all sub-arrays of length three, in the fashion of a sliding window, without disturbing the order of the values.?

For example, the result should be:
[[8,2,22],[2,22,97],[22,97,38],[97,38,15]]

Answer

You could pass a parameter for like this to achieve

a.each_con(3)

This returns an Enumeration which you may iterate over. To turn the Enumeration into an array, call the to_a method:

a.each_cons(3).to_a