Gene Gene - 10 months ago 51
Ruby Question

How do I arrange an array as table rows?

I am trying to learn the Ruby way of array processing. What is a succinct way to write the following function?

def columnize(items, n_cols)

Items is a 1D array of arbitrary length. I want to return an array of rows, each having a length of
, that includes all of the
column-wise, possibly with
s padding the last column. For example:

items = [1, 2, 3, 4, 5, 6, 7]
table = columnize items, 3

This should produce a

[[1, 4, 7],
[2, 5, nil],
[3, 6, nil]]

Note that it's possible for the last column to be all
s as in:

columnize [1, 2, 3, 4, 5, 6, 7, 8, 9], 4

This is a real problem I need to solve for report generation. I have a Ruby newbie solution that is not very satisfying and can post it if desired.

Answer Source

Except for filling rows that only have nil elements, this will do:

first, *rest = items.each_slice((items.length/n_cols).ceil).to_a*rest)