Skip to content

Instantly share code, notes, and snippets.

@Martin-Alexander
Last active July 21, 2023 15:22
Show Gist options
  • Save Martin-Alexander/57b02eee6497549e7115b712508d52cc to your computer and use it in GitHub Desktop.
Save Martin-Alexander/57b02eee6497549e7115b712508d52cc to your computer and use it in GitHub Desktop.

Reading and Writing to CSV files in Ruby

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"

Reading:

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

Writing:

When it comes to writing to a file you have some options:

  1. Append new rows to the end of the file
  2. 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"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment