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

438
Views
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 answers
Answer question

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