如何打印具有固定列宽的二维数组 [英] How to print a 2D array with fixed column width

查看:22
本文介绍了如何打印具有固定列宽的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

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

animals 只是一个例子,我的数组也可以有 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:

Assuming your array is n × m and not 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_ses 用于数组包含 nils、数字等的情况.

Note: The to_ses are used in case your arrays contain nils, numbers, etc.

这篇关于如何打印具有固定列宽的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆