Skip to content

Instantly share code, notes, and snippets.

@fronx
Last active December 10, 2015 12:29
Show Gist options
  • Select an option

  • Save fronx/4434611 to your computer and use it in GitHub Desktop.

Select an option

Save fronx/4434611 to your computer and use it in GitHub Desktop.
print tables on the console
#!/usr/bin/env ruby
def print_aligned(text, sep)
lines = text.to_s.split("\n").map do |line|
line.split(sep)
end
maxes =
lines.inject([]) do |maxes, line|
line.map(&:length).each_with_index do |length, index|
if length > maxes[index].to_i
maxes[index] = length
end
end
maxes
end
lines.each do |fields|
line =
fields.each_with_index.map do |field, index|
"%-#{maxes[index]}s"
end.join(' ') + "\n"
printf(line, *fields)
end
nil
end
<<'RUBY' # example
require 'analytics/text_utils'
include Analytics::TextUtils
table = "a,bbbbbbbbbb,c
123,0,923092384
98234,345,9"
print_aligned(table, ',')
# =>
# a bbbbbbbbbb c
# 123 0 923092384
# 98234 345 9
RUBY
print_aligned(STDIN.read, Regexp.new(ARGV.first || "\t"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment