Using ruby's CSV::Table class for the first time, I ran across this behavior, which I find odd:
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"
I assumed that since each row has headers defined that the table would respect those headers, but it seems to ignore them. Looking at the docs, I don't see a way to sort all rows in a consistent way. Is there an option or method that I'm not seeing?
It's easy enough to sort stuff consistently before creating the rows, sure, but it's also easy enough to do without the csv table class altogether--I was kinda hoping for a little more polish from a stdlib class.
The Table docs say "All rows are assumed to have the same headers.". We can see that, if the headers: keyword is not provided, then the headers are taken from the first row.
# 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