Rails键值数组到表

时间:2013-06-19 18:30:40

标签: ruby-on-rails ruby

我有这个数组我在Rails中返回

[
  ["RETURNS FUEL SURCHARGE", "236.20"],
  ["RETURNS PRINT AND MAIL LABEL", "9.00"],
  ["BILLING ADJUSTMENT FOR W/E 02/23/2013", "7.99"],
  ["SHIPPING CHARGE CORRECTION GROUND", "5471.01"],
  ["BILLING ADJUSTMENT FOR W/E 03/02/2013", "-1.43"],
  ["RETURNS 3 UPS PICKUP ATTEMPTS", "187.50"],
  ["CHARGEBACK CHARGEBACK SURCHARGE", "24.00"],
  ["BILLING ADJUSTMENT FOR W/E 03/16/2013", "-31.02"],
  ["SHIPPING CHARGE CORRECTION OVER MAXIMUM LENGTH", "50.00"],
  ["CHARGEBACK FUEL SURCHARGE", "2.44"]
]

我希望将这些信息放在表格中。我最好的方法就是迷失方向。

2 个答案:

答案 0 :(得分:3)

您需要遍历数组并为数组中的每个条目添加新的表行。因此,在您的视图中(假设此数组已分配给控制器中的@array变量),您可以循环遍历数组:

更新:根据tadman的建议添加数组解构

<table>
  <% @array.each do |description, amount| -%>
  <tr>
    <td><%= description %></td>
    <td><%= amount %></td>
  </tr>
  <% end -%>
</table>

答案 1 :(得分:1)

要回答这个问题 - 如果我想按数量对数组进行排序,我该怎么做?。是的,你可以这样做。

array = [["RETURNS FUEL SURCHARGE", "236.20"], ["RETURNS PRINT AND MAIL LABEL", "9.00"], ["BILLING ADJUSTMENT FOR W/E 02/23/2013", "7.99"], ["SHIPPING CHARGE CORRECTION GROUND", "5471.01"], ["BILLING ADJUSTMENT FOR W/E 03/02/2013", "-1.43"], ["RETURNS 3 UPS PICKUP ATTEMPTS", "187.50"], ["CHARGEBACK CHARGEBACK SURCHARGE", "24.00"], ["BILLING ADJUSTMENT FOR W/E 03/16/2013", "-31.02"], ["SHIPPING CHARGE CORRECTION OVER MAXIMUM LENGTH", "50.00"], ["CHARGEBACK FUEL SURCHARGE", "2.44"]]
array.sort_by{|i| i[1].to_i}
# => [["BILLING ADJUSTMENT FOR W/E 03/16/2013", "-31.02"],
#     ["BILLING ADJUSTMENT FOR W/E 03/02/2013", "-1.43"],
#     ["CHARGEBACK FUEL SURCHARGE", "2.44"],
#     ["BILLING ADJUSTMENT FOR W/E 02/23/2013", "7.99"],
#     ["RETURNS PRINT AND MAIL LABEL", "9.00"],
#     ["CHARGEBACK CHARGEBACK SURCHARGE", "24.00"],
#     ["SHIPPING CHARGE CORRECTION OVER MAXIMUM LENGTH", "50.00"],
#     ["RETURNS 3 UPS PICKUP ATTEMPTS", "187.50"],
#     ["RETURNS FUEL SURCHARGE", "236.20"],
#     ["SHIPPING CHARGE CORRECTION GROUND", "5471.01"]]