split array to sub array by step in Ruby

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 really miss the Python slice steps syntax 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]

Tags:

Python

Ruby