简体   繁体   中英

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.

Simplified your code a bit. 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

puts import

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 pos t and the CSV Ruby docs to learn more about working with CSV files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM