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

449
Visualizações
Ruby: How to iterate through a hash created from a csv file

I am trying to take an existing CSV file, add a fourth row to it, and then iterate through the second and third row to create the fourth rows values. Using Ruby I've created hashes where the headers are the keys and the column values are the hash values (ex: "id"=>"1", "new_fruit" => "apple")

My practice CSV file looks like this:practice csv file image

My goal is to create a fourth column: "brand_new" (which I was able to do) and then add values to it by concatenating the values from the second and third row (which I am stuck on). At the moment I just have a placement value (x) for the fourth columns values so I could see if adding the fourth column to the hash actually worked: Results with x = 1

Here is my code:

require 'csv'

def self.import  
  table = []
  CSV.foreach(File.path("practice.csv"), headers: true) do |row|
    table.each do |row| 
      row["brand_new"] = full_name
    end
    table << row.to_h
  end
  table
 end

def full_name
  x = 1
  return x
end

# Add another col, row by row:
import.each do |row|
  row["brand_new"] = full_name
end
puts import

Any suggestions or guidance would be much appreciated. Thank you.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Simplified your code a bit. I read the file first, then iterate about the read content.

Note: Change col_sep to comma or delete it to use the default if needed.

require "csv"

def self.import 
  table = CSV.read("practice.csv", headers: true , col_sep: ";")

  table.each do |row|
    row["brand_new"] = "#{row["old_fruit"]} #{row["new_fruit"]}"
  end
  puts table
end

I use the read method to read the CSV file content. It allows you to directly access the column/cell values.

Line 7 shows how to concatenate the column values as string:

"#{row["old_fruit"]} #{row["new_fruit"]}"

Refer to this old SO post and the CSV Ruby docs to learn more about working with CSV files.

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