Ruby - CSV File Read


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.


require 'csv'"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 # from  w w w .  j a  v a2  s . co m

puts'text.txt').inspect'text.txt', 'r').each do |person| 
  puts person.inspect 

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


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