patternrubyMinor
Print multiplication tables
Viewed 0 times
tablesprintmultiplication
Problem
Write a function that given a
The code is pretty straightforward, but I am interested in any possible improvement.
max argument will print a nicely aligned multiplication tables, for example, if max = 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 64The 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)Solution
Spike gave a nice answer already. I just wanted to point out one thing: This is a good use case for
This one only uses 1 space between columns, but 2 spaces can be had by replacing
rjust, aka "right-justify". With that, you can skip the string-multiplication when you pad the numbers.def print_multiplication_table(max)
padding = (max * max).to_s.length + 1
sequence = (1..max).to_a
puts sequence.product(sequence)
.map { |a, b| (a * b).to_s.rjust(padding) }
.each_slice(max)
.map(&:join)
.join("\n")
endThis one only uses 1 space between columns, but 2 spaces can be had by replacing
.map(&:join) with .map { |row| row.join(" ") }.Code Snippets
def print_multiplication_table(max)
padding = (max * max).to_s.length + 1
sequence = (1..max).to_a
puts sequence.product(sequence)
.map { |a, b| (a * b).to_s.rjust(padding) }
.each_slice(max)
.map(&:join)
.join("\n")
endContext
StackExchange Code Review Q#112171, answer score: 4
Revisions (0)
No revisions yet.