Good morning people. I'm new to Rails and I'm using google translate to post here.
I have an array
, and I would like to take a certain amount of values from the array, and put them in a new array1
, for example, the first 7 numbers, and then the next 7 numbers in the second array:
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]
How could I do this?
CodePudding user response:
You can use the Ruby shift Array method to accomplish this:
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]
Note that the shift
method edits your original array as well.
By the way, this is pure Ruby (the programming language), no Rails (the framework) here! Hope this helps.
CodePudding user response:
I think you need each_slice
here:
res = array.each_slice(7).to_a
And you will get array with subarrays length 7 each. Last element will have remaining:
# 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]
]
And then you can use each
to go through elements
res.each { |subarray| # do with subarray what you need }
Or you can get any element you want by using these methods:
first_subarray = res.first
second_subarray = res.second
last_subarray = res.last
# or by index
third_subarray = res[2]
And key thing here that your initial array
won't be reflected