如何根据每行的 headers 制作 ruby csv table 排序列?

How to make ruby csv table order columns based on headers for each row?

第一次使用 ruby 的 CSV::Table class,我 运行 发现这种行为很奇怪:

require 'csv'
r0 = CSV::Row.new(['a','b','c'], [], true)
r1 = CSV::Row.new(['a','b','c'], [10,11,12])
r2 = CSV::Row.new(['c','b','a'], [22,21,20])
t = CSV::Table.new([r0,r1,r2])
t.to_csv

# Expected Output:
# => "a,b,c\n10,11,12\n20,21,22\n"

# Actual Output:
# => "a,b,c\n10,11,12\n22,21,20\n"

我假设因为每一行都有 headers 定义,所以 table 会尊重那些 headers,但它似乎忽略了它们。查看文档,我看不到以一致的方式对所有行进行排序的方法。是否有我没有看到的选项或方法?

当然,在创建行之前对内容进行一致排序很容易,但是完全没有 csv table class 也很容易——我有点希望多一点从 stdlib class.

润色

Table 文档说“假定所有行都具有相同的 headers”。我们可以看到,如果没有提供 headers: 关键字,那么 headers 从第一行 开始 .

# csv/table.rb
class CSV
  class Table
    # Constructs a new CSV::Table from +array_of_rows+, which are expected
    # to be CSV::Row objects. All rows are assumed to have the same headers.
    def initialize(array_of_rows, headers: nil)
      # ..
      unless @headers
        # ..
          @headers = @table.first.headers