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

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

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 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