How to Read CSV Files in Ruby



In this article, you will learn how to read CSV files in Ruby.

Reading CSV files

To read a CSV file in Ruby, you can use the CSV library which comes bundled with Ruby’s standard library. Here’s an example of how to use it:

require 'csv'

# Open the CSV file
CSV.foreach('file.csv') do |row|
  # Process each row
  puts row.inspect

In this example, we’re using the foreach method to iterate through each row of the CSV file. The row variable will contain an array of values corresponding to the columns in the CSV file.

If your CSV file has a header row, you can use the headers option to automatically parse the header row and use it as keys in a hash for each subsequent row:

require 'csv'

# Open the CSV file with headers
CSV.foreach('file.csv', headers: true) do |row|
  # Access the values for each column by key
  puts row['column1']

In this example, the row variable is now a CSV::Row object that behaves like a hash, with keys corresponding to the header row and values corresponding to the values in each subsequent row.