Please note, this is a STATIC archive of website teamtutorials.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.

Click Here to Turn Your Development Passion into a Real Career.

How to parse a CSV file using ruby

Here’s a simple tip on how to parse a comma separated value or CSV file using ruby. Ruby has a standard library available that makes this task very simple. All we need to do is open a CSV file, read it, and parse it using the CSV parser that comes with ruby. Let’s say we want to import a CSV file that contains the fields: name,age,sex.

name,age,sex
john,28,m
julie,19,f
adrienne,42,f
rob,16,m

First off I create the csv file above and saved it as test.csv. Next we need to get started with ruby.

In order to parse this CSV I am going to use the build in CSV library, so we need to require the CSV library.

require 'csv'

Next we need to read the file and store it to a variable

require 'csv'

csv_text = File.read('test.csv')

Now we’re going to tell the CSV library to parse the file, and that the file has headers. When we specify that headers exist, the parse will use the first row as the names for each value.

require 'csv'

csv_text = File.read('test.csv')
csv = CSV.parse(csv_text, :headers => true)

Now, we just need to loop through each record and perform whatever task it is we want to do with the data. In this case I just output to the terminal window using puts.

require 'csv'

csv_text = File.read('test.csv')
csv = CSV.parse(csv_text, :headers => true)

csv.each do |row|										
	puts "Name: #{row['name']} - Age: #{row['age']} -  Sex: #{row['sex']}"
end

As you can see above when we run: csv.each do |row|, that sets the variable row to an array of all the values in the row. It also will use the names from the first column. So to get a certain field we just need to use row[‘fieldname’].

When you run this in the terminal (ruby csv.rb) you should see something like this:

jward-laptop:Desktop jward$ ruby csv.rb
Name: john - Age: 28 -  Sex: m
Name: julie - Age: 19 -  Sex: f
Name: adrienne - Age: 42 -  Sex: f
Name: rob - Age: 16 -  Sex: m