1

我正在尝试向 Ruby 1.9 中的 CSV::Table 添加一行(这些问题也适用于 Ruby 1.8 中的 FasterCSV)。如果新行中的列顺序与表中的不同,则即使正确指定了标题,元素也会添加到错误的列中。看起来好像新行中的标题被忽略了。

require 'csv'

first_row = CSV::Row.new(["h1","h2","h3"],[1,2,3])
second_row = CSV::Row.new(["h2","h1","h3"],[2,1,3]) # note the change in order
table = CSV::Table.new([first_row])
table << second_row
puts table.to_s

输出:

h1,h2,h3
1,2,3
2,1,3

但由于我明确指定了标题,我希望 CSV 将新行的标题与表的标题相匹配并产生以下输出:

h1,h2,h3
1,2,3
1,2,3

有什么解释吗?除了在创建新行之前自己重新排序列之外,我还能做些什么吗?

4

2 回答 2

0

正如scuawn 的回答中提到的,CSV::Table#to_csv 方法无法按您的预期工作。

但是 CSV::Table中的数据放置在正确的列中!根据您的示例,您可能会发现这是真的:

irb(main):1:0> table.entries
=> [#<CSV::Row "h1":1 "h2":2 "h3":3>, #<CSV::Row "h2":2 "h1":1 "h3":3>]
irb(main):2:0> table.headers
=> ["h1", "h2", "h3"]
irb(main):3:0> table.values_at(*table.headers)
=> [[1, 2, 3], [1, 2, 3]]
于 2011-07-18T22:14:01.710 回答
0

源代码 CSV::Table#to_csv 中的解释。

我是 Ruby 新手,但试试我的补丁:

--- csv.rb.old  2011-07-18 23:24:38.184913108 +0600
+++ csv.rb  2011-07-18 23:23:54.972802099 +0600
@@ -836,7 +836,7 @@
         if row.header_row?
           rows
         else
-            rows + [row.fields.to_csv(options)]
+            rows + [row.fields(*headers).to_csv(options)]
         end
       end.join
     end

输出:

h1,h2,h3
1,2,3
1,2,3
于 2011-07-18T17:28:32.480 回答