split array to sub array by step in Ruby

python, ruby

Solution

a = [1,2,3,4,5,6,7,8,9]
a.values_at(*(1...7).step(2)) - [nil]
#=> [2, 4, 6] 

Although in the above case the `- [nil]` part is not necessary, it serves just in case your range exceeds the size of the array, otherwise you may get something like this:

a = [1,2,3,4,5,6,7,8,9]
a.values_at(*(1..23).step(2))
#=> [2, 4, 6, 8, nil, nil, nil, nil, nil, nil, nil, nil]

Problem

In Python i can slice array with "jump-step". Example: ``` In [1]: a = [1,2,3,4,5,6,7,8,9] In [4]: a[1:7:2] # start from index = 1 to index < 7, with step = 2 Out[4]: [2, 4, 6] ``` Can Ruby do it?

Original source