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 = []
array3 = []
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]
array2 = [1,2,3,4,5,6,7]
array3 = [8,9,10,11,12,13,14]
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.shift(7) # array2 is now [1, 2, 3, 4, 5, 6, 7]
array3 = array.shift(7) # array3 is now [8, 9, 10, 11, 12, 13, 14]
res = array.each_slice(7).to_a
# outputs below
[
[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]
]
res.each { |subarray| # do with subarray what you need }
first_subarray = res.first
second_subarray = res.second
last_subarray = res.last
# or by index
third_subarray = res[2]
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]
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]
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]
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]]
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]
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]]