Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Right align numbers in table printing

  • Loading branch information...
commit e7ff71627bcd79470070928949f82b71a54d8c0b 1 parent 4d30f3a
tomhuda authored
Showing with 14 additions and 4 deletions.
  1. +12 −2 lib/thor/shell/basic.rb
  2. +2 −2 spec/shell/basic_spec.rb
View
14 lib/thor/shell/basic.rb
@@ -122,8 +122,11 @@ def print_table(table, options={})
colcount = table.max{|a,b| a.size <=> b.size }.size
+ maximas = []
+
start.upto(colcount - 2) do |i|
- maxima ||= table.map {|row| row[i] ? row[i].to_s.size : 0 }.max
+ maxima = table.map {|row| row[i] ? row[i].to_s.size : 0 }.max
+ maximas << maxima
formats << "%-#{maxima + 2}s"
end
@@ -134,7 +137,14 @@ def print_table(table, options={})
sentence = ""
row.each_with_index do |column, i|
- sentence << formats[i] % column.to_s
+ maxima = maximas[i]
+
+ if column.is_a?(Numeric)
+ f = "%#{maxima}s "
+ else
+ f = formats[i]
+ end
+ sentence << f % column.to_s
end
sentence = truncate(sentence, options[:truncate]) if options[:truncate]
View
4 spec/shell/basic_spec.rb
@@ -173,7 +173,7 @@ def shell
TABLE
end
- it "prints a table with small numbers" do
+ it "prints a table with small numbers, and right-aligns them" do
table = [
["Name", "Number", "Color"],
["Erik", 1, "green"]
@@ -181,7 +181,7 @@ def shell
content = capture(:stdout){ shell.print_table(table) }
content.should == <<-TABLE
Name Number Color
-Erik 1 green
+Erik 1 green
TABLE
end
Please sign in to comment.
Something went wrong with that request. Please try again.