csv help

C

charlie bowman

Can anyone point me to a good tutorial on csv files and ruby. I've read
the docs that go along with the standard csv library but it's hard to
put it all together. I'm trying to write a simple timekeeper application
using csv files but I don't really know where to start. Maybe someone
can point out the many flaws in this beginners attempt. Currently all
I'm trying to do is create a row of time data each time the app is ran.

require 'csv'
class TimeKeeper

## constant of where the csv file is stored
@@csv_file = "/shared/home/cmbowma/.timeclock"

def initialize
end

def read
@data = String.new
CSV.parse open(@@csv_file).read do |row|
@data << row.to_s << ','
end
@data
end

def write(data)
writer = CSV.open(@@csv_file, 'w')
writer << data
writer.close
end
end

csv = TimeKeeper.new
@data = csv.read.to_a
time = Time.now
@data << [time]
csv.write(@data)
 
J

James Edward Gray II

def read
@data = String.new
CSV.parse open(@@csv_file).read do |row|
@data << row.to_s << ','
end
@data
end

To read a CSV file into an Array, try:

array_of_csv_rows = CSV.read("my_file.csv")

If you want to read CSV row by row, use:

CSV.foeach("my_file.csv") do |row
# use row here
end

Hope that helps.

James Edward Gray II
 
G

Gene Tani

charlie said:
Can anyone point me to a good tutorial on csv files and ruby. I've read
the docs that go along with the standard csv library but it's hard to
put it all together.

Here's some stuff to look at:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/166736
http://redhanded.hobix.com/bits/howDoYouParseTabSeparatedValues.html
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/163345

pickax 2, page 663 discusses CSV lib

http://rubyforge.org/projects/fastercsv/
http://www.linuxdevcenter.com/pub/a/linux/2003/09/18/ruby_csv.html?page=1
 

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

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top