Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!