"Unflattening" arrays

F

Farrel Lifson

Hi folks,

Is there an easy way to get [1,2,3,4,5,6,7,8] into
[[1,2],[3,4],[5,6],[7,9]] or [[1,2,3,4],[5,6,7,8]] depending on a
parameter?

Farrel
 
D

Daniel Harple

Is there an easy way to get [1,2,3,4,5,6,7,8] into
[[1,2],[3,4],[5,6],[7,9]] or [[1,2,3,4],[5,6,7,8]] depending on a
parameter?

require 'enumerator'

[1,2,3,4,5,6,7,8].enum_for:)each_slice, 4).to_a # -> [[1, 2, 3, 4],
[5, 6, 7, 8]]

-- Daniel
 
S

Sylvain Joyeux

Check Enumerable#each_slice

require 'enumerator'
[1,2,3,4,5,6,7,8].enum_for:)each_slice, 2).to_a
 
A

Andrew Johnson

Hi folks,

Is there an easy way to get [1,2,3,4,5,6,7,8] into
[[1,2],[3,4],[5,6],[7,9]] or [[1,2,3,4],[5,6,7,8]] depending on a
parameter?

From 'enumerator.rb' , #each_slice(n) lets you iterate over successive
slices, and #enum_slice(n) generates an enumerator which you can use
the #to_a on to get the array of slices:

require 'enumerator'
a = [1,2,3,4,5,6,7,8,9]
a.enum_slice(2).to_a # => [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
a.enum_slice(4).to_a # => [[1, 2, 3, 4], [5, 6, 7, 8], [9]]

andrew
 
W

William James

Farrel said:
Hi folks,

Is there an easy way to get [1,2,3,4,5,6,7,8] into
[[1,2],[3,4],[5,6],[7,9]] or [[1,2,3,4],[5,6,7,8]] depending on a
parameter?

Farrel

[1,2,3,4,5,6,7,8].inject([[]]){|a,x|
a.last.size==2 ? a << [x] : a.last << x ; a }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,351
Latest member
RoxiePulli

Latest Threads

Top