填充表格数据的打印输出

时间:2009-03-02 16:47:12

标签: arrays ruby formatting

我知道这可能很简单,但我在一个文件中有一些这样的数据:

Artichoke

Green Globe, Imperial Star, Violetto

24" deep

Beans, Lima

Bush Baby, Bush Lima, Fordhook, Fordhook 242

12" wide x 8-10" deep

我希望能够格式化成一个漂亮的TSV类型的表,看起来像这样:

    Name  | Varieties    | Container Data
----------|------------- |-------
some data here nicely padded with even spacing and right aligned text 

7 个答案:

答案 0 :(得分:18)

尝试String#rjust(width)

"hello".rjust(20)           #=> "               hello"

答案 1 :(得分:18)

我写了一个宝石来完成这个:http://tableprintgem.com

答案 2 :(得分:16)

没有人提到过最酷的" /最紧凑的方式 - 使用%运算符 - 例如:"%10s %10s" % [1, 2]。这是一些代码:

xs = [
  ["This code", "is", "indeed"],
  ["very", "compact", "and"],
  ["I hope you will", "find", "it helpful!"],
]
m = xs.map { |_| _.length }
xs.each { |_| _.each_with_index { |e, i| s = e.size; m[i] = s if s > m[i] } }
xs.each { |x| puts m.map { |_| "%#{_}s" }.join(" " * 5) % x }

给出:

      This code          is          indeed
           very     compact             and
I hope you will        find     it helpful!

以下代码更具可读性:

max_lengths = xs.map { |_| _.length }
xs.each do |x|
  x.each_with_index do |e, i|
    s = e.size
    max_lengths[i] = s if s > max_lengths[i]
  end
end
xs.each do |x|
  format = max_lengths.map { |_| "%#{_}s" }.join(" " * 5)
  puts format % x
end

答案 3 :(得分:7)

这是一个相当完整的例子,假设如下

  • 您的产品列表包含在名为veg.txt
  • 的文件中
  • 您的数据按照每条记录的三行排列,并且字段位于连续行

我有点像铁杆,所以毫无疑问会有更好,更优雅的方式来做这件事

#!/usr/bin/ruby

class Vegetable

  @@max_name ||= 0  
  @@max_variety ||= 0  
  @@max_container ||= 0  

  attr_reader :name, :variety, :container

  def initialize(name, variety, container)
    @name = name
    @variety = variety
    @container = container  

    @@max_name = set_max(@name.length, @@max_name)  
    @@max_variety = set_max(@variety.length, @@max_variety)  
    @@max_container = set_max(@container.length, @@max_container)
  end

  def set_max(current, max)
    current > max ? current : max
  end

  def self.max_name  
    @@max_name  
  end  

  def self.max_variety  
    @@max_variety  
  end  

  def self.max_container()  
    @@max_container  
  end  

end

    products = []


    File.open("veg.txt") do | file|

      while name = file.gets
        name = name.strip
        variety = file.gets.to_s.strip
        container = file.gets.to_s.strip
        veg = Vegetable.new(name, variety, container)
        products << veg
      end
    end

    format="%#{Vegetable.max_name}s\t%#{Vegetable.max_variety}s\t%#{Vegetable.max_container}s\n"
    printf(format, "Name", "Variety", "Container")
    printf(format, "----", "-------", "---------")
    products.each do |p|
        printf(format, p.name, p.variety, p.container)
    end

以下示例文件

Artichoke
Green Globe, Imperial Star, Violetto
24" deep
Beans, Lima
Bush Baby, Bush Lima, Fordhook, Fordhook 242
12" wide x 8-10" deep
Potatoes
King Edward, Desiree, Jersey Royal
36" wide x 8-10" deep

产生以下输出

       Name                                      Variety                Container
       ----                                      -------                ---------
  Artichoke         Green Globe, Imperial Star, Violetto                 24" deep
Beans, Lima Bush Baby, Bush Lima, Fordhook, Fordhook 242    12" wide x 8-10" deep
   Potatoes           King Edward, Desiree, Jersey Royal    36" wide x 8-10" deep

答案 4 :(得分:3)

我有一个小功能来打印2D数组作为表格。每行必须具有相同的列数才能使其工作。根据您的需求调整也很容易。

def print_table(table)
  # Calculate widths
  widths = []
  table.each{|line|
    c = 0
    line.each{|col|
      widths[c] = (widths[c] && widths[c] > col.length) ? widths[c] : col.length
      c += 1
    }
  }
  # Indent the last column left.
  last = widths.pop()
  format = widths.collect{|n| "%#{n}s"}.join(" ")
  format += " %-#{last}s\n"
  # Print each line.
  table.each{|line|
    printf format, *line
  }
end

答案 5 :(得分:3)

另一颗宝石:https://github.com/visionmedia/terminal-table 终端表是一个快速,简单但功能丰富的ASCII表生成器,用Ruby编写。

答案 6 :(得分:0)

Kernel.sprintf应该让你开始。