Last active
December 10, 2015 12:29
-
-
Save fronx/4434611 to your computer and use it in GitHub Desktop.
print tables on the console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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