The*_*pes 11 ruby arrays formatting
我知道这可能很简单,但我在一个文件中有一些这样的数据:
Artichoke
Green Globe, Imperial Star, Violetto
24" deep
Beans, Lima
Bush Baby, Bush Lima, Fordhook, Fordhook 242
12" wide x 8-10" deep
Run Code Online (Sandbox Code Playgroud)
我希望能够格式化成一个漂亮的TSV类型的表,看起来像这样:
Name | Varieties | Container Data
----------|------------- |-------
some data here nicely padded with even spacing and right aligned text
Run Code Online (Sandbox Code Playgroud)
Dav*_* J. 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
这是一个相当完整的例子,假设如下
我对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
Run Code Online (Sandbox Code Playgroud)
以下示例文件
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
| 归档时间: |
|
| 查看次数: |
17800 次 |
| 最近记录: |