Ruby - CSV File Read

Introduction

CSV stands for comma-separated values.

For each item of data you're storing, you can have multiple attributes separated with commas.

In the following code we create a CSV file.

Each line represents a different person, and commas separate the attributes relating to each person.

The commas allow you to access each attribute separately.

Ruby's standard library includes a library called csv to use text files containing CSV data.

Demo

require 'csv' 

File.open("test.txt", "w") do |f| 
  f.puts "Java,Manager,Logic,45\n" 
  f.puts "Json,Data,Female,23\n" 
  f.puts "Database,DBA,Female,38\n" 
end #   w ww  .  j  a  va 2 s .  c o  m

puts CSV.read('text.txt').inspect 

CSV.open('text.txt', 'r').each do |person| 
  puts person.inspect 
end 

people = CSV.parse(File.read('text.txt')) 
puts people[0][0] 
puts people[1][0] 
puts people[2][0]

Result

CSV.parse converts the data into an array of arrays.

The elements in the main array represent each line in the file.

Each element in those elements represents a different attribute of that line.

Related Topics