Gene Gene - 1 month ago 7
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
n_cols
, that includes all of the
items
column-wise, possibly with
nil
s padding the last column. For example:

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


This should produce a
table
of:

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


Note that it's possible for the last column to be all
nil
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

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

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