I haven't used the CSV module before either, but looking into it this
test script I came up with parses a CSV source file, writing it to a
new array. Then you can append to that new array and write the results
back to the original CSV file. It's not pretty and might not be the
most Rubyish way of getting the job done but it worked for me using
Ruby 1.8.2 on Win32. Try it out and let me know...
require 'csv'
# test.csv consists of three comma delimited fields, something like:
#
# 1,"Greg","Admin"
# 2,"Joe","User"
# 3,"Jim","Admin"
new_array = []
temp_array = []
reader = CSV.open('test.csv', 'r') do |row|
(0...row.nitems).each do |item|
temp_array.push(row[item].data)
end
new_array << temp_array
temp_array = []
end
new_items = [4,"Jane","User"]
new_array << new_items
CSV.open('test.csv', 'w') do |writer|
new_array.each do |row|
writer << row
end
end
Bil Kleb wrote:
> ChrisH wrote:
> > Bil Kleb wrote:
> > ...
> >> She says that she can't figure out how to /append/
> >> to a CSV file using Ruby's standard library.
> > ...
> >
> > Wouldn't it just be a matter of opening the file in append mode?
>
> It would, but unfortunately CSV doesn't support 'a'
> or 'a+', viz, lib/ruby/1.8/csv.rb,
>
> 83 def CSV.open(path, mode, fs = nil, rs = nil, &block)
> 84 if mode == 'r' or mode == 'rb'
> 85 open_reader(path, mode, fs, rs, &block)
> 86 elsif mode == 'w' or mode == 'wb'
> 87 open_writer(path, mode, fs, rs, &block)
> 88 else
> 89 raise ArgumentError.new("'mode' must be 'r', 'rb', 'w', or 'wb'")
> 90 end
> 91 end
>
> Later,
> --
> Bil
> http://fun3d.larc.nasa.gov