Skip to content

Instantly share code, notes, and snippets.

@jferris
Created January 14, 2010 22:04
Show Gist options
  • Select an option

  • Save jferris/277557 to your computer and use it in GitHub Desktop.

Select an option

Save jferris/277557 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
lines = STDIN.readlines
leading_match = lines.first.match(/^\s+/)
leading = leading_match ? leading_match[0] : ''
lines_without_edges = lines.map { |line| line.strip.sub(/^\|/, '').sub(/\|$/, '') }
lines_without_edges.reject! { |line| line.empty? }
table = lines_without_edges.map { |line| line.split('|').map { |cell| cell.strip } }
cell_count = table.first.size
widths = (0...cell_count).map do |index|
table.inject(0) do |result, row|
size = row[index].size
size > result ? size : result
end
end
aligned_table = table.map do |row|
result = []
row.each_with_index do |cell, index|
result << cell.ljust(widths[index])
end
result
end
aligned_lines = aligned_table.map do |row|
leading + '| ' + row.join(" | ") + ' |'
end
puts aligned_lines.join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment