FroggyFreshh FroggyFreshh - 6 months ago 11
Ruby Question

How to print a 2D array with fixed columns

I have an array:

animals = [["cats","dogs"],["verrylongcat","dog"],["shortcat","verrylongdog"],["cat","dog"]]
==>
cats dogs
verrylongcat dog
shortcat verrylongdog
cat dog


This is not really nicely displayed. 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

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 nxm and not 2xm:

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 }