# Integer to array of chunks

• A+
Category：Languages

I need to turn an integer into an array of intervals. For example,

``number_to_steps(number: 10, step: 3) # => [[0, 2], [3, 5], [6, 8], [9, 9]]  number_to_steps(number: 7, step: 2) # => [[0, 1], [2, 3], [4, 5], [6, 6]]  number_to_steps(number: 8, step: 2) # => [[0, 1], [2, 3], [4, 5], [6, 7]] ``

I tried:

``def number_to_ranges(number:, size:)     chunks = ((number - 1) / size.to_f).ceil      (0..chunks - 1).map do |index|       from = index * size       to = (index + 1) * size - 1        [ from, to > number ? number : to ]     end   end ``

But it doesn't work properly. For example,

``number_to_ranges(number: 14, step: 4) [[0, 3], [4, 7], [8, 11], [12, 14]] ``

should not go to 14.

Any idea?

An alternative (to your method) would be to use `each_slice`.

``def number_to_steps(number:, step:)   (0...number).each_slice(step).map { |arr| [arr.first, arr.last] } end ``

Tests:

``number_to_steps(number: 10, step: 3)  #=> [[0, 2], [3, 5], [6, 8], [9, 9]]  number_to_steps(number: 7, step: 2)  #=> [[0, 1], [2, 3], [4, 5], [6, 6]]  number_to_steps(number: 8, step: 2)  #=> [[0, 1], [2, 3], [4, 5], [6, 7]] ``