Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split array to sub array by step in Ruby

Tags:

python

ruby

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?

like image 881
Dang Tung Lam Avatar asked Apr 26 '13 08:04

Dang Tung Lam


People also ask

Can you split an array Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

What is .first in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


2 Answers

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]
like image 96
Arup Rakshit Avatar answered Sep 21 '22 00:09

Arup Rakshit


In ruby, to get the same output:

a = [1,2,3,4,5,6,7,8,9]
(1...7).step(2).map { |i| a[i] }
=> [2, 4, 6] 
like image 3
seph Avatar answered Sep 24 '22 00:09

seph