olafsadventures
olafsadventures

Reputation: 151

Remove n elements from array dynamically and add to another array

nums= [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]
new_array=[]

How do I grab every two items divisible by 5 and add them to a new array. This is the desired result: the new_array should now contain these values

      [[5,10],[15,20],[25,30]]

Note: I want to do this without pushing them all into the array and then performing array.each_slice(2). The process should happen dynamically.

Upvotes: 2

Views: 52

Answers (1)

akuhn
akuhn

Reputation: 27813

Try this

new_array = nums.select { |x| x % 5 == 0 }.each_slice(2).entries

No push involved.

Upvotes: 2

Related Questions