Ruby part consumes part by part

Say I have an array with n elements. I want to take the first ten elements and do something with them, and then the next ten and so on until the array is executed.

What is the right way for Ruby to do this? (With a c-language background, I could write some for and loop within the loop, up to ten, do things and set my accounting variable to zero and continue processing the main array.)

+3
source share
1 answer
#!/usr/bin/ruby1.8

a = (1..10).to_a
a.each_slice(3) do |slice|
  p slice    # => [1, 2, 3]
             # => [4, 5, 6]
             # => [7, 8, 9]
             # => [10]
end
+11
source

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


All Articles