Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda