Reputation: 33380
I need to reverse an array in chunks of a specified size. Here is an example of what needs to happen:
chunk = 2
arr = [1,2,3,4,5]
How can I build an array in which chunks are reversed like this:
[2, 1, 4, 3, 5]
My code:
arr.each_slice(chunk) { |a| p a }
outputs:
[1,2]
[3,4]
[5]
Each of the chunks above needs to be reversed and appended to a final array as seen above.
Upvotes: 0
Views: 119
Reputation: 118289
arr = [1,2,3,4,5]
arr.each_slice(2).flat_map(&:reverse)
# => [2, 1, 4, 3, 5]
Upvotes: 2