0

Possible Duplicate:
Best way to read CSV in Ruby. FasterCSV?

Is it possible to have Ruby read through a CSV file, line by line and use the contents of the line to set as different variables?

e.g. one line is Matt,Masters,18-04-1993 and I want to split the line and use:

  • Matt = firstname
  • Masters = surname
  • 18-04-1993 = dob

so far I have:

require 'uri/http'
require 'csv'

File.open("filename.csv").readlines.each do |line|

d = line.split(",")

puts d

end
Community
  • 1
  • 1
Matt Masters
  • 15
  • 1
  • 4

2 Answers2

10

You should be able to do it

File.open("filename.csv").readlines.each do |line|
  CSV.parse do |line|
    firstname, surname, dob = line
    #you can access the above 3 variables now
  end
end

Now will be able to use firstname, surname and dob in the block.

HungryCoder
  • 7,506
  • 1
  • 38
  • 51
1

Maybe you're looking for something like this...

File.open("filename.csv").read.split("\n").each do |line|
  first_name, last_name, age = line.split(",")
  # do something
end
Aaron J
  • 51
  • 7