打印列间距的二维数组
接受具有 to_s 方法(字符串整数浮点数和布尔值..)和可选边距宽度整数的对象的二维数组。
更新:它现在适用于不同长度的数组。
def print_table(table, margin_width = 2)
# the margin_width is the spaces between columns (use at least 1)
column_widths = []
table.each do |row|
row.each.with_index do |cell, column_num|
column_widths[column_num] = [column_widths[column_num] || 0, cell.to_s.size].max
end
end
puts (table.collect do |row|
row.collect.with_index do |cell, column_num|
cell.to_s.ljust(column_widths[column_num] + margin_width)
end.join
end)
end
注意: puts 语句后面的括号是必需table.collect
的,因此do end
块不会作为两个单独的参数传递给 puts 方法。
示例表
my_table = [
["1", "Animal", "Dog", "1"],
[1, "Animal", "Cat", "2"],
[1, "Animal", "Bird", "3"],
[2, "Place", "USA", "1"],
[2.5, "Place", "Other", "2"],
[3, "Color", "Red"],
[3, "Color", "Blue", "b"],
[3, "Some more color", "Orange", "c"],
[4.7, "Age", "Young", "a"],
[4, "Age", "Middle", "b"],
[4, "Age", "Old", "c"],
[5, "Alive"],
[],
[5, "Alive", false, "n"]
]
print_table my_table
印刷:
1 Animal Dog 1
1 Animal Cat 2
1 Animal Bird 3
2 Place USA 1
2.5 Place Other 2
3 Color Red
3 Color Blue b
3 Some more color Orange c
4.7 Age Young a
4 Age Middle b
4 Age Old c
5 Alive
5 Alive false n
(没有上色。上面的颜色是由 StackOverflow 添加的。)