These are the very basics of reading and writing to CSV files in Ruby. For more details and other available options consider checking out the full documentation: here
Consider a given csv file scientists.csv
with the following content:
Isaac,Newton
James,Maxwell
Max,Planck
Before we begin don't forget to:
require "csv"
Use the foreach
method as follows to iterate through each row of the csv file
CSV.foreach("scientists.csv") do |row|
p row
end
#=> ["Isaac", "Newton"]
#=> ["James", "Maxwell"]
#=> ["Max", "Planck"]
Alternatively, you can simply access the content of the csv file as an array of arrays wherein each sub-array contains the content of a row
csv_file_contents = CSV.read("scientists.csv")
p csv_file_contents
#=> [["Isaac", "Newton"], ["James", "Maxwell"], ["Max", "Planck"]]
When it comes to writing to a file you have some options:
- Append new rows to the end of the file
- Delete all existing rows and write from scratch
In both cases we're going to use the open
method
Let's append two new scientists to the end of the file (notice the "a"
argument)
CSV.open("scientists.csv", "a") do |csv|
csv << ["Albert", "Einstein"]
csv << ["Galileo", "Galilei"]
end
# Now lets read the contents of the csv file:
p CSV.read("scientists.csv")
#=> [["Isaac", "Newton"], ["James", "Maxwell"], ["Max", "Planck"], ["Albert", "Einstein"], ["Galileo", "Galilei"]]
Now, let's write from scratch (notice the "w"
argument). This means we'll be deleting all previous rows before inserting the new ones
CSV.open("scientists.csv", "w") do |csv|
csv << ["Erwin", "Schrödinger"]
csv << ["Werner", "Heisenberg"]
end
# Now lets read the contents of the csv file:
p CSV.read("scientists.csv")
#=> [["Erwin", "Schrödinger"], ["Werner", "Heisenberg"]]