是否有内置方法或gem可以按列打印Ruby数组?

问题描述 投票:0回答:6

我有一个大型 Ruby 数组,我想按列打印它,就像 Unix 'ls' 命令的默认输出(至少在 OS X 上)。是否有 gem 或内置方法可以做到这一点?我知道 Awesome_print 宝石。它有一些性感的输出,但似乎不提供专栏。

ruby pretty-print
6个回答
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
投票

除了我的第一个成熟的可配置解决方案之外,还有一个基于元素最大字符串长度的较短解决方案

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                    |

1
投票

我同意评论者 Sean 的观点,但我就是无法控制住自己,而是控制住了我的小便来生下这个小可爱,我使用的是 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|

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

0
投票

@peter 解决方案的一些改进:

  1. 如果调用者不是数组的数组,则引发异常;
  2. 将任何值类型转换为字符串,它将适用于包含字符串和数字混合的数组;
  3. 任何列分隔符字符串都可以指定为参数;
  4. 输出是一个格式化为表格的字符串,因此可以进一步处理它,并且如果不需要输出,也不会破坏任何内容。
class Array

  # Convert an Array of arrays into a String, formatted as a table.
  def columnize(sep="  ")
    each{|r| r.is_a? Array or raise NoMethodError, "Must be called on an Array of arrays."}
    s = ""
    l = []
    each{|r|r.each_with_index{|f,i| l[i] = [l[i]||0, f.to_s.length].max}}
    each{|r|r.each_with_index{|f,i| s << "#{f.to_s.ljust l[i]}#{sep}"}; s << "\n"}
    return s
  end
 
 end
 

被称为喜欢

puts [["field", 2, 3, "another field"],[4,5,"looooooooooonger","short one"]].columnize(" | ")

产生这个输出

field | 2 | 3                | another field | 
4     | 5 | looooooooooonger | short one     | 

0
投票

这是来自 @Claudio Floreani 的代码,经过一些清理。

class Array
  # Convert an Array of Array into a String, formatted as a table.
  def columnize(separator = '  ')
    each { |row| row.is_a? Array or raise NoMethodError, 'Must be called on an Array of Array.' }
    result = ''
    l = []
    each { |row| row.each_with_index { |f, i| l[i] = [l[i] || 0, f.to_s.length].max } }
    each do |row|
      row.each_with_index { |f, i| result << "#{f.to_s.ljust l[i]}#{separator}" }
      result << "\n"
    end
    result
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.