Align columns: Difference between revisions

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