在 Ruby 1.9 中将 CSV::Row 添加到 CSV::Table 时,标题的含义是什么?
我正在尝试向 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
有任何解释吗?除了在创建新行之前自行重新排序列之外,我还能做些什么吗?
I am trying to add a row to a CSV::Table in Ruby 1.9 (the questions also applies to FasterCSV in Ruby 1.8). If the order of the columns is different in the new row than in the table, the elements are added to the wrong columns, even if the headers are correctly specified. It looks as if the headers in the new row are ignored.
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
Output:
h1,h2,h3
1,2,3
2,1,3
But since I am specifying the headers explicitly, I would expect CSV to match the headers of the new row to those of the table and produce this output:
h1,h2,h3
1,2,3
1,2,3
Any explanations? Can I do something about it other than reordering the columns myself before creating a new row?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
源代码中的解释 CSV::Table#to_csv。
我是 Ruby 新手,但请尝试我的补丁:
输出:
The explanation in the source code CSV::Table#to_csv.
I'm novice in Ruby, but try my patch:
Output:
如scuawn 的回答,CSV::Table#to_csv 方法无法按您的预期工作。
但是 CSV::Table 中的数据放置在正确的列中!根据您的示例,您可能会发现这是真的:
As mentioned in scuawn's answer, CSV::Table#to_csv method does not work as you are expecting.
However data in CSV::Table are placed in proper columns ! Based on your example, you may see that's true: