Split an array into an additional array in Ruby

In Python, I can cut an array using a 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 this?

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

Although the - [nil] part - [nil] not needed in the above case, it serves just in case your range exceeds the size of the array, otherwise you might 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] 
+6
source

In ruby, to get the same result:

 a = [1,2,3,4,5,6,7,8,9] (1...7).step(2).map { |i| a[i] } => [2, 4, 6] 
+2
source

If you really missed the syntax of the Python snippet steps, you can get Ruby to do something very similar.

 class Array alias_method :brackets, :[] def [](*args) return brackets(*args) if args.length != 3 start, stop, step = *args self.values_at(*(start...stop).step(step)) end end arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr[1,7,2] #=> [2, 4, 6] 
+2
source

Source: https://habr.com/ru/post/943687/


All Articles