FroggyFreshh FroggyFreshh - 6 months ago 14
Ruby Question

How to print a 2D array with fixed column width

I have an array:

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
is just an example, my array could also have 3, or 4 columns or even more.

ndn ndn
Answer

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.


Assuming your array is n × m and not 2 × m:

animal_max_sizes = animals.first.size.times.map do |index|
  animals.transpose[index].max_by(&:size).size
end

animals.map do |animal_line|
  animal_line.each.with_index.reduce('') do |animal_line, (animal, index)|
    animal_line + animal.ljust(animal_max_sizes[index].next)
  end
end.each { |animal_line_stringified| puts animal_line_stringified }
Comments