Align columns: Difference between revisions
Content added Content deleted
Line 3,807: | Line 3,807: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<lang ruby> |
<lang ruby>J2justifier = {'L' => :ljust, |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
J2justifier = {'L' => String.instance_method(:ljust), |
|||
⚫ | |||
⚫ | |||
=begin |
=begin |
||
Justify columns of textual tabular input where the record separator is the newline |
Justify columns of textual tabular input where the record separator is the newline |
||
Line 3,830: | Line 3,819: | ||
=end |
=end |
||
def aligner(infile, justification = 'L') |
def aligner(infile, justification = 'L') |
||
⚫ | |||
fieldsbyrow = infile.map {|line| line.strip.split('$')} |
fieldsbyrow = infile.map {|line| line.strip.split('$')} |
||
# pad to same number of fields per record |
# pad to same number of fields per record |
||
maxfields = fieldsbyrow.map |
maxfields = fieldsbyrow.map(&:length).max |
||
fieldsbyrow.map! {|row| |
fieldsbyrow.map! {|row| row + ['']*(maxfields - row.length)} |
||
row + ['']*(maxfields - row.length) |
|||
} |
|||
# calculate max fieldwidth per column |
# calculate max fieldwidth per column |
||
colwidths = fieldsbyrow.transpose.map {|column| |
colwidths = fieldsbyrow.transpose.map {|column| |
||
column.map |
column.map(&:length).max |
||
} |
} |
||
# pad fields in columns to colwidth with spaces |
# pad fields in columns to colwidth with spaces |
||
⚫ | |||
fieldsbyrow.map |
fieldsbyrow.map {|row| |
||
row.zip(colwidths).map {|field, width| |
row.zip(colwidths).map {|field, width| |
||
field.send(justifier, width) |
|||
} |
}.join(" ") |
||
} |
}.join("\n") |
||
fieldsbyrow.map {|row| row.join(" ")}.join("\n") |
|||
end |
end |
||
require 'stringio' |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
for align in %w{Left Right Center} |
for align in %w{Left Right Center} |