我知道这可能很简单,但我在一个文件中有一些这样的数据:
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
MarkusQ.. 18
试试String#rjust(width)
:
"hello".rjust(20) #=> " hello"
Chris Doyle.. 18
我写了一个宝石来做到这一点:http://tableprintgem.com
试试String#rjust(width)
:
"hello".rjust(20) #=> " hello"
我写了一个宝石来做到这一点:http://tableprintgem.com
没有人提到"最酷"/最紧凑的方式 - 使用%
运营商 - 例如:"%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
这是一个相当完整的例子,假设如下
您的产品列表包含在名为veg.txt的文件中
您的数据按每条记录排列三行,并且字段在连续的行上
我对rails来说有点像菜鸟,所以毫无疑问会有更好,更优雅的方式来做到这一点
#!/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