>>201431
#!/usr/bin/env ruby
require 'csv'
require 'optparse'
class Array
def rightpad!(min_size, padding = nil)
concat([padding] * (min_size - size)) if size < min_size
return self
end
def hline(┌, ─, ┬, ┐)
┌ +
case ─
when Array then ─.zip(self).map { |─, col_size| ─.ljust(col_size) }
when String then self.map { |n| ─ * n }
end.join(┬) +
┐
end
end
OptionParser.new do |opts|
opts.banner = "Usage: ruby #{File.basename __FILE__} [options] [file]"
opts.separator <<-EOF
Reads CSV file or standard input and prints pretty table with Unicode
Box Drawing characters.
Options:
EOF
opts.on "-h", "--help", "Prints this help." do puts opts; exit; end
end.parse!
case ARGV.length
when 0 then # pass
when 1 then STDIN.reopen ARGV[0]
else raise "More than 1 file specified. What do you expect me to do?"
end
rows = CSV.new(STDIN).read
n_cols = rows.map(&:size).max
rows.each { |row| row.rightpad!(n_cols, "") }
col_sizes = rows.transpose.map { |col| col.map(&:length).max }
puts col_sizes.hline(*%W{┌ ─ ┬ ┐})
for row in rows
puts col_sizes.hline("│", row, "│", "│")
puts col_sizes.hline(*%W{├ ─ ┼ ┤}) unless row.equal? rows.last
end
puts col_sizes.hline(*%W{└ ─ ┴ ┘})