Parsing a CSV in Ruby

Parsing is CSV file in Ruby is very easy. Check out this code:

require "csv"
csv_file_path = "ABSOLUTE_PATH_TO_YOUR_CSV_FILE"
file = File.open(csv_file_path, "r:ISO-8859-1")
csv = CSV.parse file

That’s it. This is how you get the first row:

csv.first

This is how you get the first column of the first row:

csv.first.first

And this is how you iterate over all rows:

csv.each do |row|
  p row
end

Easy! Right?

One thought on “Parsing a CSV in Ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s