[ create a new paste ] login | about

Link: http://codepad.org/L7oTwff4    [ raw code | fork ]

Ruby, pasted on May 29:
#!/usr/bin/env ruby

require 'optparse'
 

in_delim, out_delim = ' '   , ' | '
no_strip, squeeze   = false , false
justify , left_rows = :ljust, false

OptionParser.new do |opts|
  opts.banner = "Usage: #{ARGV[0]} [options]"
  opts.on('-d', '--in_delim  [STRING]' , 'Specify column delimiter'){ |d| in_delim  = d }
  opts.on('-o', '--out_delim [STRING]' , 'Specify output delimiter'){ |o| out_delim = o }
  opts.on('-r', '--regex     [REGEX]'  , 'Specify regex-delimiter' ){ |r| in_delim  = Regexp.compile r }
  opts.on('-n', '--no-strip'           , 'Do not strip columns'    ){ no_strip      = true }
  opts.on('-s', '--squeeze'        , 'Squeeze adjacent delimiters' ){ squeeze       = true }
  opts.on('-l', '--left-justify-rows'  , 'Left-justify rows'       ){ left_rows     = true }
  opts.on('-j', '--justify   [L|R|C]', [:ljust, :rjust, :center], 'Justify columns'){ |j| justify = j }
end.parse!


def expand_table tbl, padder
  tbl.map{|elem| padder[elem, tbl.map(&:length).max]}
end

pad_string = Proc.new  { |str, len| str.send(justify, len) }

pad_array  = Proc.new do |arr, len|
  blanks = [''] * (len - arr.length)
  left_rows ? blanks + arr : arr + blanks
end


rows = STDIN.readlines.map do
|row|
  res = row.chomp!.split in_delim, -1
  res.map!(&:strip)        unless no_strip
  res.reject!{|col| col == ''} if squeeze
  res
end

expanded_rows = expand_table rows, pad_array
expanded_cols = expanded_rows.transpose.map{ |col| expand_table col, pad_string }
result_rows   = expanded_cols.transpose.map{ |row| row.join out_delim }

puts result_rows


Output:
No errors or program output.


Create a new paste based on this one


Comments: