Padding printed output of tabular data Padding printed output of tabular data ruby ruby

Padding printed output of tabular data


No one has mentioned the "coolest" / most compact way -- using the % operator -- for example: "%10s %10s" % [1, 2]. Here is some code:

xs = [  ["This code", "is", "indeed"],  ["very", "compact", "and"],  ["I hope you will", "find", "it helpful!"],]m = xs.map { |_| _.length }xs.each { |_| _.each_with_index { |e, i| s = e.size; m[i] = s if s > m[i] } }xs.each { |x| puts m.map { |_| "%#{_}s" }.join(" " * 5) % x }

Gives:

      This code          is          indeed           very     compact             andI hope you will        find     it helpful!

Here is the code made more readable:

max_lengths = xs.map { |_| _.length }xs.each do |x|  x.each_with_index do |e, i|    s = e.size    max_lengths[i] = s if s > max_lengths[i]  endendxs.each do |x|  format = max_lengths.map { |_| "%#{_}s" }.join(" " * 5)  puts format % xend