[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

"Unflattening" arrays

Farrel Lifson

3/27/2006 7:59:00 PM

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


6 Answers

Daniel Harple

3/27/2006 8:08:00 PM

0

On Mar 27, 2006, at 9:59 PM, Farrel Lifson wrote:

> 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


Sylvain Joyeux

3/27/2006 8:09:00 PM

0

Check Enumerable#each_slice

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

--
Sylvain Joyeux


matthew.moss.coder

3/27/2006 8:10:00 PM

0

require 'enumerator'

> a = []
> (1..8).to_a.each_slice(2) { |x| a << x }
> p a
=> [[1, 2], [3, 4], [5, 6], [7, 8]]


Andrew Johnson

3/27/2006 8:24:00 PM

0

On Tue, 28 Mar 2006 04:59:00 +0900, Farrel Lifson <farrel.lifson@gmail.com>
wrote:

> 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

--
Andrew L. Johnson http://www.s...
What have you done to the cat? It looks half-dead.
-- Schroedinger's wife

Farrel Lifson

3/27/2006 8:27:00 PM

0

On 3/27/06, Daniel Harple <dharple@generalconsumption.org> wrote:

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

This is just what I need. Thanks!


William James

3/27/2006 8:54:00 PM

0

Farrel Lifson wrote:
> 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 }