如何以固定的列宽打印2D数组 [英] How to print a 2D array with fixed column width
本文介绍了如何以固定的列宽打印2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组:
animals = [
["cats", "dogs"],
["verrylongcat", "dog"],
["shortcat", "verrylongdog"],
["cat", "dog"]
]
我想很好地显示它。有没有一种简单的方法可以将列固定为固定宽度,所以我得到这样的东西:
And I would like to display it nicely. Is there an easy way to make the colums a fixed width so I get something like this:
cats dogs
verrylongcat dog
shortcat verrylongdog
cat dog
动物
只是一个例子,我的数组也可以具有3或4列甚至更多。
animals
is just an example, my array could also have 3, or 4 columns or even more.
推荐答案
您正在寻找 String#ljust
:
You are looking for String#ljust
:
max_cat_size = animals.map(&:first).max_by(&:size).size
animals.each do |cat, dog|
puts "#{cat.ljust(max_cat_size)} #{dog}"
end
如果要多个空间,只需在插值中添加相应的量即可。
If you want more than one space just add the corresponding amount in the interpolation.
假定数组为 n×m 而不是 2×m :
animal_max_sizes = animals.first.size.times.map do |index|
animals.transpose[index].map(&:to_s).max_by(&:size).size
end
animals.map do |animal_line|
animal_line.each.with_index.reduce('') do |animal_line, (animal, index)|
animal_line + animal.to_s.ljust(animal_max_sizes[index].next)
end
end.each { |animal_line_stringified| puts animal_line_stringified }
注意: to_s
es用于数组中包含 nil
s,数字等的情况。
Note: The to_s
es are used in case your arrays contain nil
s, numbers, etc.
这篇关于如何以固定的列宽打印2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文