Forum: Ruby "Unflattening" arrays

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2006-03-27 21:59
(Received via mailing list)
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
9358cc96c46055cd68d4a76a9aefe026?d=identicon&s=25 Daniel Harple (Guest)
on 2006-03-27 22:08
(Received via mailing list)
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
934180817a3765d132193a5428f99051?d=identicon&s=25 Sylvain Joyeux (Guest)
on 2006-03-27 22:09
(Received via mailing list)
Check Enumerable#each_slice

require 'enumerator'
[1,2,3,4,5,6,7,8].enum_for(:each_slice, 2).to_a
81d609425e306219d54d793a0ad98bce?d=identicon&s=25 Matthew Moss (Guest)
on 2006-03-27 22:10
(Received via mailing list)
require 'enumerator'

> a = []
> (1..8).to_a.each_slice(2) { |x| a << x }
> p a
=> [[1, 2], [3, 4], [5, 6], [7, 8]]
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2006-03-27 22:26
(Received via mailing list)
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!
5c841628b56df3a68984986e9f095d01?d=identicon&s=25 Andrew Johnson (andrew)
on 2006-03-27 22:29
(Received via mailing list)
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
2ee1a7960cc761a6e92efb5000c0f2c9?d=identicon&s=25 William James (Guest)
on 2006-03-27 22:59
(Received via mailing list)
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 }
This topic is locked and can not be replied to.