How to read CSV in Ruby 1.9.2

T

Tom Llobrera

I am totally new to rails. I have a school project that requires me to
import data from a CSV file to mysql database. I read the documentation
regarding CSV in ruby 1.9 but I don't understand since I am very new to
to this. Can someone show me a very simple example how to read data from
CSV file using the ruby 1.9 CSV. I know this might be too much to ask
but I really need help. Pls be patient with me... Pls..


Tom
 
C

Chris Kottom

[Note: parts of this message were removed to make it a legal post.]

Simple example...

require "csv" # require the CSV library
CSV.foreach("path/to/file.csv") do |row| # open your file and loop through
the rows
p row # print each row's contents
p row.count # count the number of values in
each row (CSV::Row is Enumerable)
...
end
 
J

James Edward Gray II

Simple example...
=20
require "csv" # require the CSV library
CSV.foreach("path/to/file.csv") do |row| # open your file and loop = through
the rows
p row # print each row's contents
p row.count # count the number of values = in
each row (CSV::Row is Enumerable)
...
end

Taking that one step further, an import using Rails 3 usually goes =
something like this:

require "csv"
CSV.new( params[:file].tempfile,
:headers =3D> true,
:header_converters =3D> :symbol ).each do |row|
MyModel.create!(row.to_hash)
end

Hope that helps.

James Edward Gray II=
 
C

Catsquotl

I wondered that myself last week and came up with..

@a = []
f = File.open("#{filename}", "r")
f.readlines.each {|e|
e.chomp!
b=e.split(";") #or comma's if you prefer.
@a.push(b)
}
f.close

This gives you an array of arrays.

Eelco
(I gues i should search the api more.. Didn't know about the CVS
class/module)..

Op 16-2-2011 6:55, Tom Llobrera schreef:
 
T

Thomas Preymesser

[Note: parts of this message were removed to make it a legal post.]

I wondered that myself last week and came up with..
this code is not really a good solution

@a = []
f = File.open("#{filename}", "r")

this could be much simpler written as File.open(filename,"r")

f.readlines.each {|e|
e.chomp!
b=e.split(";") #or comma's if you prefer.

with this line you get rather false results if you have a string value in a
csv file which contains ',' oder ';'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top