Forum: Ruby csv help

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Charlie B. (Guest)
on 2006-01-27 23:17
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)
James G. (Guest)
on 2006-01-27 23:26
(Received via mailing list)
On Jan 27, 2006, at 3:18 PM, charlie bowman wrote:

>   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 G. II
This topic is locked and can not be replied to.