From: dblack@... Date: 2006-11-07T22:27:37+09:00 Subject: Re: dividing an array Hi -- On Tue, 7 Nov 2006, Jan Svitok wrote: > On 11/7/06, Brad Tilley wrote: >> Say I have an array that contains 144 strings. I want to divide the array >> into >> 12 sub-arrays each containing 12 strings. What is the Ruby Way of doing >> this? >> I've looked at slice array[0..11] etc, but that seems a bit clunky. >> >> Thank you, >> Brad >> > > require 'enumerator' > > ret = [] > array.each_slice(12) {|a| ret << a} I wish there were a nice way to do this without the temporary array. One of the first add-on methods I ever wrote for my own use in Ruby was "in_chunks_of": [1,2,3,4,5,6].in_chunks_of(2) => [ [1,2], [3,4], [5,6] ] The ActiveSupport library has something similar (in_groups_of). I think it would be a handy addition to Array. David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org