Christian Genco

ruby

Read a CSV file with Ruby #

require 'csv'

CSV.parse(File.read("table.csv"), headers: true).map(&:to_hash).each{|line|
  p line
  puts line["title"]
}

Write a CSV file #

require 'csv'

data = [
  {name: "John Doe", age: 30, city: "New York"},
  {name: "Jane Smith", age: 25, city: "Los Angeles"}
]


CSV.open(filename, "wb") do |csv|
  keys = data.map(&:keys).flatten.uniq
  csv << keys
  each do |item|
    csv << keys.map{|k| item[k]}
  end
end