将数据放在特定标题中

时间:2011-03-04 09:35:34

标签: ruby-on-rails ruby pdf pdf-generation prawn

headers = ["05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22"] 

data = ["05:01", "05:23", "05:43", "06:03", "06:33", "06:53", "07:03", "07:23", "07:46", "08:04", "08:24", "08:44", "09:14", "09:24", "09:44", "10:19", "10:39", "11:02", "11:22", "11:42", "12:12", "12:32", "12:52", "13:12", "13:32", "13:52", "14:12", "14:32", "14:42", "15:02", "15:32", "15:52", "16:12", "16:32", "16:52", "17:12", "17:32", "17:52", "18:12", "18:47", "19:23", "19:48", "20:28", "21:03", "21:33", "22:08", "22:40"] 

我必须将特定数据放到正确的标题中。例如

    05    06

    05:01 06:03
    05:23 06:33
    05:43 06:53

Rails 3.0.3
Ruby 1.9.2
Prawn 0.8.4

我怎么能这样做?

基本上我想做这样的事情。

Prawn::Document.generate(path) do
  table([['05','06']] + [['05:01','06:03'],['05:23','06:33'],['05:43','06:53']], :header => true) do
  end
end

2 个答案:

答案 0 :(得分:2)

mapped_headers = headers.map do |header|
  data_array = data.select {|d| header == d[0,2]}
  [header, data_array]
end

此代码将提供如下输出:

[["05", ["05:01", "05:23", "05:43"]], ["06", ["06:03", "06:33", "06:53"]], ["07", ["07:03", "07:23", "07:46"]], ["08", ["08:04", "08:24", "08:44"]], ["09", ["09:14", "09:24", "09:44"]], ["10", ["10:19", "10:39"]], ["11", ["11:02", "11:22", "11:42"]], ["12", ["12:12", "12:32", "12:52"]], ["13", ["13:12", "13:32", "13:52"]], ["14", ["14:12", "14:32", "14:42"]], ["15", ["15:02", "15:32", "15:52"]], ["16", ["16:12", "16:32", "16:52"]], ["17", ["17:12", "17:32", "17:52"]], ["18", ["18:12", "18:47"]], ["19", ["19:23", "19:48"]], ["20", ["20:28"]], ["21", ["21:03", "21:33"]], ["22", ["22:08", "22:40"]]]

您还可以通过编辑最后一行

来创建哈希
{header => data_array}

你可以通过这样做来实现对虾的要求

rows = 3
datas = (0...rows).map do |row|
  mapped_headers.map{|header| header[1][row]}
end
Prawn::Document.generate(path) do
  table([headers] + datas, :header => true) do
  end
end

答案 1 :(得分:0)

如果您询问如何向数组添加新元素,方法push将完成这项工作:

headers.push "05"
data.push "05:01"