FroggyFreshh FroggyFreshh - 6 months ago 23
Ruby Question

Ruby, print out a 2d array with fixed columns

So what I have now is an array like this

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


So as you can see 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


thnx alot in advance :)

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.


EDIT: 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 }
Comments