1 comments

@Cary Swoveland 2019-05-15 15:45:04

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 |

@tadman 2019-05-15 15:46:19

Not '%-2d' % n?

@Sergio Tulentsev 2019-05-15 17:30:42

Or you could use String#ljust / String#rjust.

@Cary Swoveland 2019-05-15 19:55:19

@Sergio, that's what I started with. Changed it to please tadman.

@Sergio Tulentsev 2019-05-15 20:00:57

@CarySwoveland: ah, I see. TIL then. :)

Related Questions

Sponsored Content

12 Answered Questions

[SOLVED] How to make --no-ri --no-rdoc the default for gem install?

  • 2009-09-04 21:48:59
  • Ricardo Acras
  • 248165 View
  • 1040 Score
  • 12 Answer
  • Tags:   ruby rubygems

20 Answered Questions

[SOLVED] How to call shell commands from Ruby

  • 2008-08-05 12:56:52
  • CodingWithoutComments
  • 527000 View
  • 1076 Score
  • 20 Answer
  • Tags:   ruby shell interop

18 Answered Questions

[SOLVED] How to pass command line arguments to a rake task

49 Answered Questions

[SOLVED] Vertically align text to top within a UILabel

10 Answered Questions

[SOLVED] How to convert a string to lower or upper case in Ruby

24 Answered Questions

[SOLVED] How to write a switch statement in Ruby

2 Answered Questions

5 Answered Questions

[SOLVED] Right aligning digits in c?

  • 2015-01-26 00:39:34
  • adty4
  • 7156 View
  • 1 Score
  • 5 Answer
  • Tags:   c text-alignment

1 Answered Questions

[SOLVED] python 3 string formatting (alignment)

Sponsored Content