FroggyFreshh FroggyFreshh - 10 months ago 29
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

is just an example, my array could also have 3, or 4 columns or even more.

ndn ndn

You are looking for String#ljust:

max_cat_size =
animals.each do |cat, dog|
  puts "#{cat.ljust(max_cat_size)} #{dog}"

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 = do |index|
end do |animal_line|
  animal_line.each.with_index.reduce('') do |animal_line, (animal, index)|
    animal_line + animal.ljust(animal_max_sizes[index].next)
end.each { |animal_line_stringified| puts animal_line_stringified }