-2

Im making a program where you give 2 inputs, the amount of columns and amount of rows to a multiplikation-system. But when having bigger numbers (2 digit numbers) it makes the system unaligned.

Theres nothing wrong with the code. All I want is something that makes the "|" aligned vertically.

I want the output to be;

| 3 | 6  | 9  |
| 4 | 8  | 12 |
| 6 | 12 | 18 |

But I get the output;

| 3 | 6 | 9 |
| 4 | 8 | 12 |
| 6 | 12 | 18 |
cassavvi
  • 1
  • 1

1 Answers1

1
arr = [3, 6, 9, 4, 8, 12, 6, 12, 18]
nrows = 3

width = arr.minmax.map { |n| n.to_s.size }.max
  #=> 2

puts arr.each_slice(nrows).map { |row| '| ' +
  row.map { |n| "%-#{width}d" % n }.join(' | ') + ' |' }
| 3  | 6  | 9  |
| 4  | 8  | 12 |
| 6  | 12 | 18 |

Perhaps you'd prefer to right-adjust:

puts arr.each_slice(nrows).map { |row| '| ' +
  row.map { |n| "%#{width}d" % n }.join(' | ') + ' |' }
|  3 |  6 |  9 |
|  4 |  8 | 12 |
|  6 | 12 | 18 |

See Kernel#sprintf for formatting directives. If it is known that all elements of arr are non-negative we could write:

width = arr.max.to_s.size
  #=> 2

If you wish to make each column as narrow as possible, adjusting right, you could do the following.

arr = [3, 6, 9, 4, -81, 12, 6, 12, 1800]
nrows = 3

col_widths = nrows.times.map { |i|
  (i..nrows*nrows-1).step(3).map { |j| arr[j].to_s.size }.max }
  #=> [1, 3, 4]

puts arr.each_slice(nrows).map { |row| '| ' +
  row.map.with_index { |n,i| "%#{col_widths[i]}d" % n }.join(' | ') + ' |' }
| 3 |   6 |    9 |
| 4 | -81 |   12 |
| 6 |  12 | 1800 |
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100