theCrab theCrab - 1 month ago 4
Ruby Question

How to format columns so they line using ruby

I have Ruby arrays inside an array that look like below:

More data info is here https://gist.github.com/theCrab/6064789

The column headers are style, colour, size, desc, qty, min_qty, req_qty, root_sku, offset_size


[
["UD/BOYS-TR/SENIOR/STANDARD", "*BLACK/2SHORT LEG", "28\" W", "29\"LEG STD MENS TROUSER", -10, 4, 14, "00001955", 1],
["UD/BOYS-TR/SENIOR/STANDARD", "*BLACK/2SHORT LEG", "30\" W", "29\"LEG STD MENS TROUSER", -14, 6, 20, "00001955", 2],
["UD/BOYS-TR/SENIOR/STANDARD", "*BLACK/2SHORT LEG", "32\" W", "29\"LEG STD MENS TROUSER", -29, 6, 35, "00001955", 3],
["UD/BOYS-TR/SENIOR/STANDARD", "*BLACK/3REG LEG", "28\" W", "31\"LEG STD MENS TROUSER", 0, 3, 3, "00001976", 1],
["UD/BOYS-TR/SENIOR/STANDARD", "*BLACK/3REG LEG", "30\" W", "31\"LEG STD MENS TROUSER", -12, 5, 17, "00001976", 2],
["UD/BOYS-TR/SENIOR/STANDARD", "*BLACK/3REG LEG", "32\" W", "31\"LEG STD MENS TROUSER", -6, 6, 12, "00001976", 3]
]


I want to print a nicely formated table that looks like below:

style | colour | size | desc | qty | min_qty | req_qty | root_sku
-----------------------------------------------------------------
standd| red | 28 W | N/a | 4 | 5 | 1 | 00001955
| | 30 W | N/a | 9 | 5 | 4 | 00001955
| | 36 W | N/a | 10 | 5 | 5 | 00001955
| blue | 28 W | N/a | 4 | 5 | 1 | 00001955
| | 30 W | N/a | 9 | 5 | 4 | 00001955
| | 36 W | N/a | 10 | 5 | 5 | 00001955
fitted| red/blu| 28 W | N/a | 4 | 5 | 1 | 00001954
| | 30 W | N/a | 9 | 5 | 4 | 00001954
| | 36 W | N/a | 10 | 5 | 5 | 00001954
| blue | 28 W | N/a | 4 | 5 | 1 | 00001954
| | 30 W | N/a | 9 | 5 | 4 | 00001954
| | 36 W | N/a | 10 | 5 | 5 | 00001954


How can I best run through the Array and accomplish this feat?

GSP GSP
Answer

Ruby has a string formatting functionality that, I think, derives from the old C-style sprintf function. http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-sprintf and http://ruby-doc.org/core-2.0/String.html#method-i-25

In the String class you use the % method and pass in an array.

outer_array.each do |inner_array|
  puts ('%6s|%8s|%5s|%6s|%4d|%8d|%6d|%10d' % inner_array)
end

(P.S. I just guessed on the formatting so you'll need to refine as necessary)

Comments