How to Read CSV File in Ruby?

It is common to have tabular data stored in CSV (Comma Separated Values) files. In Ruby, one can handle CSV files without much ado because the built-in libraries make it easy to do so. This article focuses on discussing the ways to read a CSV file in Ruby.

Approach to Read CSV Files in Ruby?

There are multiple approaches to reading CSV files with Ruby, but the most widely used method is through the built-in CSV library. The latter facilitates parsing and manipulation of CSV data.

Syntax:

require ‘csv’

Implementation

data.csv

ID, Name, Age1, John, 302, Alice, 253, Bob, 354, Sarah, 28

data.csv

Below is the Ruby program to read the “data.csv” file:

Ruby
require 'csv'

# Path to your CSV file
csv_file_path = 'data.csv'

# Open the CSV file and iterate through each row
CSV.foreach(csv_file_path, headers: true) do |row|
  
  # Access data in each row using headers
  id = row['ID']
  name = row['Name']
  age = row['Age']
  
  # Print each row to the console
  puts "ID: #{id}, Name: #{name}, Age: #{age}"
end

Output:

Output

Explanation:

  1. CSV.foreach provides a way for opening your CSV file and iterating over each row in it.
  2. Inside that block that represents an instance for every row containing array values. You can then go on to process these values as you need them.

Contact Us