如何格式化列,以便使用ruby进行排序

时间:2013-07-24 14:19:49

标签: arrays ruby formatting

我在一个数组中有Ruby数组,如下所示:

此处有更多数据信息https://gist.github.com/theCrab/6064789

列标题为样式颜色尺寸 desc 数量 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]
]

我想要打印一个结构良好的表,如下所示:

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

如何才能最好地运行数组并完成此专长?

1 个答案:

答案 0 :(得分:2)

Ruby有一个字符串格式化功能,我认为它源于旧的C风格sprintf函数。 http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-sprintfhttp://ruby-doc.org/core-2.0/String.html#method-i-25

在String类中,您使用%方法并传入一个数组。

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

(P.S。我刚猜到格式化,所以你需要根据需要进行改进)