module Columnize
def self.columnize(*args)
* whether to format as an array - with surrounding [] and
* whether to left justify text instead of right justify
* whether to ignore terminal codes in text size calculation
* A format specify for formatting each item each array item to a string
* a line suffix
* a line prefix
* a column separator
* the line display width
separated by two spaces. Options are available for setting
Each column is only as wide as necessary. By default, columns are
]
09, 10,
07, 08,
05, 06,
03, 04,
[01, 02,
:displaywidth => 10) =>
puts (1..10).to_a.columnize(:arrange_array => true, :colfmt => '%02d',
Formatted as an array using format specifier '%02d':
['1', '2,', '3', '4'] => '1 2\n3 4\n'
a.columnize(:arrange_vertical => false) =>
Arranged horizontally:
a.columnize => '1 3\n2 4\n'
Alternatively:
Columnize.columnize(a) => '1 3\n2 4\n'
a = (1..4).to_a
For example, for a line width of 4 characters (arranged vertically):
that when printed the columns are aligned.
Return a string from an array with embedded newlines formatted so
Columnize.columize([args]) => String
def self.columnize(*args) list = args.shift opts = parse_columnize_options(args) Columnizer.new(list, opts).columnize end
def self.included(base)
def self.included(base) # screw class variables, we'll use an instance variable on the class singleton class << base attr_accessor :columnize_opts end base.columnize_opts = DEFAULT_OPTS.dup end
def self.parse_columnize_options(args)
are in the order: +displaywidth+, +colsep+, +arrange_vertical+,
In the older style positional arguments are used and the positions
newer style, +args+ is a hash where each key is one of the option names.
Options parsing routine for Columnize::columnize. In the preferred
def self.parse_columnize_options(args) if 1 == args.size && args[0].kind_of?(Hash) # explicitly passed as a hash args[0] elsif !args.empty? # passed as ugly positional parameters. Hash[args.zip([:displaywidth, :colsep, :arrange_vertical, :ljust, :line_prefix]).map(&:reverse)] else {} end end
def columnize(*args)
def columnize(*args) return Columnize.columnize(*args) if args.length > 1 opts = args.empty? ? {} : args.pop @columnize_opts ||= self.class.columnize_opts.dup @columnizer ||= Columnizer.new(self, @columnize_opts) # make sure that any changes to list or opts get passed to columnizer @columnizer.list = self unless @columnizer.list == self @columnizer.opts = @columnize_opts.merge(opts) unless @columnizer.opts == @columnize_opts and opts.empty? @columnizer.columnize end