2
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.

1 Answer 1

2

Try this

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

No push involved.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there any way to do it w/o each slice?
Why do you want to avoid each_slice?
Because I am going to try the same thing only this time using hash keys and values... Just wondering.
Hash supports each_slice too, just give it a try.
I wasn't aware of Enumerable#entries. I see it's the same thing as Enumerable#to_a. Olaf, one way to avoid using Enumerable#each_slice here is the following: nums.select { |x| x % 10 == 0 }.map { |n| [n-5, n] }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.