Skip to content

Instantly share code, notes, and snippets.

Created April 13, 2011 06:58
Show Gist options
  • Save anonymous/917096 to your computer and use it in GitHub Desktop.
Save anonymous/917096 to your computer and use it in GitHub Desktop.
Formats Tab-separated text so that it aligns to columns with a fixed width font, retains tabs
#!/usr/bin/ruby
class Array
def transpose
width = self.map {|e| e.length}.max
trans = []
(0..width - 1).each do |col|
self.each do |row|
element = row[col]
(trans[col] ||= []) << element
end
end
trans
end
end
class NilClass
def length
0
end
end
rows = $<.read.split(/\n/).map {|line| line.split /\t/}
columns = rows.transpose
lengths = columns.map {|c| c.map{|e| e.length}.max }
padded_columns = (0 .. columns.length - 1).to_a.map do |index|
width = lengths[index]
columns[index].map do |element|
(element || "") + (" " * ((width) - element.length))
end
end
padded_columns.transpose.each do |row|
puts row.join("\t")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment