【问题标题】:What's the meaning of the headers when adding a CSV::Row to a CSV::Table in Ruby 1.9?在 Ruby 1.9 中将 CSV::Row 添加到 CSV::Table 时,标题的含义是什么?
【发布时间】:2011-07-18 14:49:10
【问题描述】:

我正在尝试向 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

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

【问题讨论】:

    标签: ruby csv fastercsv


    【解决方案1】:

    源代码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
    

    【讨论】:

    • 非常感谢 scuawn,您的补丁运行良好。另请参阅我对戴维斯回答的评论。
    【解决方案2】:

    正如scuawn's answer 中所述,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]]
    

    【讨论】:

    • 谢谢,这很有帮助。但是,我现在认为 CSV::Table 只是 CSV::Rows 的集合,没有严格的列概念。当您调用 values_at() 时,会发生正确的列排序。如果您使用 table.by_col[0] 来获取第一列,您仍然会得到 [1,2] 而不是 [1,1]。
    • 我同意 #to_csv 代码甚至 #
    猜你喜欢
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2015-12-02
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2017-04-05
    相关资源
    最近更新 更多