This is a card in Dave's Virtual Box of Cards.
Ruby: Printing N things per line from a list
Page created: 2025-07-24
back to ruby
For some reason, I keep having a need to write Ruby scripts that output lists in reasonably-sized columns.
The key is to use Ruby’s Array slice()
method to get the list in chunks.
This example doesn’t print pretty aligned columns, it just prints a certain quantity of items per line:
require 'json' # Read a JSON file with a couple thousand items in an array: jsonf = File.read('data-ordered-emoji.json') list = JSON.parse(jsonf) # Print in columns of 30 items col=30 i=0 while i < list.length joined = list.slice(i, col).join(" ") puts(joined) i += col end
As you can see, slice()
allows you to specify a length in the second
parameter which extends beyond the length of the list without complaint, which
is very handy.
See also ruby-json