RosettaCodeData/Task/Align-columns/Ruby/align-columns.rb

44 lines
1.4 KiB
Ruby
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
J2justifier = {Left: :ljust, Right: :rjust, Center: :center}
2013-04-10 14:58:50 -07:00
=begin
Justify columns of textual tabular input where the record separator is the newline
and the field separator is a 'dollar' character.
2015-11-18 06:14:39 +00:00
justification can be Symbol; (:Left, :Right, or :Center).
2013-04-10 14:58:50 -07:00
Return the justified output as a string
=end
2015-11-18 06:14:39 +00:00
def aligner(infile, justification = :Left)
2013-04-10 14:58:50 -07:00
fieldsbyrow = infile.map {|line| line.strip.split('$')}
# pad to same number of fields per record
2015-02-20 00:35:01 -05:00
maxfields = fieldsbyrow.map(&:length).max
fieldsbyrow.map! {|row| row + ['']*(maxfields - row.length)}
2013-04-10 14:58:50 -07:00
# calculate max fieldwidth per column
colwidths = fieldsbyrow.transpose.map {|column|
2015-02-20 00:35:01 -05:00
column.map(&:length).max
2013-04-10 14:58:50 -07:00
}
# pad fields in columns to colwidth with spaces
2015-02-20 00:35:01 -05:00
justifier = J2justifier[justification]
fieldsbyrow.map {|row|
2013-04-10 14:58:50 -07:00
row.zip(colwidths).map {|field, width|
2015-02-20 00:35:01 -05:00
field.send(justifier, width)
}.join(" ")
}.join("\n")
2013-04-10 14:58:50 -07:00
end
2015-02-20 00:35:01 -05:00
require 'stringio'
textinfile = <<END
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
END
2015-11-18 06:14:39 +00:00
for align in [:Left, :Right, :Center]
2013-04-10 14:58:50 -07:00
infile = StringIO.new(textinfile)
puts "\n# %s Column-aligned output:" % align
2015-11-18 06:14:39 +00:00
puts aligner(infile, align)
2013-04-10 14:58:50 -07:00
end