Here are three ways to do that.
Use Array#slice!
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
array2 = array.slice!(0,7)
#=> [1, 2, 3, 4, 5, 6, 7]
array3 = array.slice!(0,7)
#=> [8, 9, 10, 11, 12, 13, 14]
Now,
array
#=> [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
# 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
If array
is not to be mutated use Array#slice and add an additional variable (say, array1
).
array2 = array.slice(0..6)
#=> [1, 2, 3, 4, 5, 6, 7]
array3 = array.slice(7..13)
#=> [8, 9, 10, 11, 12, 13, 14]
array1 = array.slice(14..)
#=> [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
# 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
Use Enumerable#slice_before
i = 0
array2, array3, array = array.slice_before { [8, 15].include?(i += 1) }.to_a
#=> [[1, 2, 3, 4, 5, 6, 7],
# [8, 9, 10, 11, 12, 13, 14],
# [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
# 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]]
Now,
array2
#=> [1, 2, 3, 4, 5, 6, 7]
array3
#=> [8, 9, 10, 11, 12, 13, 14]
array
#=> [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
# 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
If array
is not to be mutated replace array
with array1
on the left side of the equals sign.
Partition indices and use Array#values_at
array2, array3, array = [[*0..6], [*7..13], [*14..(array.size-1)]].
map { |a| array.values_at(*a) }
#=> [[1, 2, 3, 4, 5, 6, 7],
# [8, 9, 10, 11, 12, 13, 14],
# [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
# 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]]
If array
is not to be mutated replace array
with array1
on the left side of the equals sign.