Write a function that given a
max
argument will print a nicely aligned multiplication tables, for example, ifmax = 8
1 2 3 4 5 6 7 8 2 4 6 8 10 12 14 16 3 6 9 12 15 18 21 24 4 8 12 16 20 24 28 32 5 10 15 20 25 30 35 40 6 12 18 24 30 36 42 48 7 14 21 28 35 42 49 56 8 16 24 32 40 48 56 64
The code is pretty straightforward, but I am interested in any possible improvement.
def print_multiplication_table(max)
pad = (1 + (max*max).to_s.length)
puts (1..max)
.to_a
.product((1..max).to_a)
.map{|a, b| a * b}
.each_slice(max)
.map{ |x| x.map(&:to_s).map{ |x| " " * (pad - x.length) + x}.join(' ')}
.join("\n")
end
print_multiplication_table(8)