Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda