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?
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.
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.
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With