我有一个大型的Ruby数组,我想在列中打印,就像Unix''ls'命令的默认输出一样(至少在OS X上)。有没有宝石或内置方法可以做到这一点?我知道awesome_print gem。它有一些性感的输出,但它似乎没有提供列。
答案 0 :(得分:7)
Enumerable#each_slice可能是你的朋友。
$ irb
irb> a = (0..18).to_a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
irb> a.each_slice(5) { |row| puts row.map{|e| "%5d" % e}.join(" ") }
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18
如果您希望在列中排序,可以使用切片和Enumerable#zip
irb> cols = a.each_slice((a.size+2)/3).to_a
=> [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18]]
irb> cols.first.zip( *cols[1..-1] ).each{|row| puts row.map{|e| e ? '%5d' % e : ' '}.join(" ") }
0 7 14
1 8 15
2 9 16
3 10 17
4 11 18
5 12
6 13
答案 1 :(得分:1)
我同意评论者肖恩,但我只是不能握住mysef,而是让我的小便给这个可爱的小便,我在Windows上所以不知道ls的输出是如何相似但是我确定那里这里有足够的选项来提供所需的输出
cm = {'headers' => ['first', 'second', 'third', 'fourth'], 'width' => [5, 5, 16, 30], 'separator' => '|', 'align' => [:left,:right,:left,:right]}
a = [["on", "two", "three", "a loooooooooooooooonger field"],["four","five","looooooooooonger","short one"]]
cm['headers'].each_with_index{|header, index|w = cm['width'][index];print "#{cm['align'][index]==:left ? header.ljust(w)[0..w-1]:header.rjust(w)[0..w-1]}#{cm['separator']}"}
puts ""
a.each do |record|
record.each_with_index do |field, index|
w = cm['width'][index]
print "#{cm['align'][index]==:left ? field.ljust(w)[0..w-1]:field.rjust(w)[0..w-1]}#{cm['separator']}"
end
puts ""
end
给出
first|secon|third | fourth|
on | two|three | a loooooooooooooooonger field|
four | five|looooooooooonger| short one|
答案 2 :(得分:1)
除了我的第一个完整的可配置解决方案,还有一个基于元素的最大字符串长度的较短的解决方案
class Array
def to_table l = []
self.each{|r|r.each_with_index{|f,i|l[i] = [l[i]||0, f.length].max}}
self.each{|r|r.each_with_index{|f,i|print "#{f.ljust l[i]}|"};puts ""}
end
end
[["on", "two", "three", "a loooooooooooooooonger field"],["four","five","looooooooooonger","short one"]].to_table
给出
on |two |three |a loooooooooooooooonger field|
four|five|looooooooooonger|short one |
答案 3 :(得分:0)
我认为使用hirb
更有用:
require 'hirb'
Hirb.enable :output=>{"Array"=>{:class=>Hirb::Helpers::Table}} #=> true
[[1,2], [2,3]]
+---+---+
| 0 | 1 |
+---+---+
| 1 | 2 |
| 2 | 3 |
+---+---+
2 rows in set
[[5,6,3,4]]
+---+---+---+---+
| 0 | 1 | 2 | 3 |
+---+---+---+---+
| 5 | 6 | 3 | 4 |
+---+---+---+---+
1 row in set