Forum: Ruby Problem writing a Faster_csv generated record to a file

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.
54ee59d05d2b1bf0dd8c644ea586df00?d=identicon&s=25 thiel (Guest)
on 2009-02-11 13:36
(Received via mailing list)
Hi,

I have a problem writing a record generated with FasterCSV to a file:

This is the code:

op = File.new("C:/Test/testmap.csv", "w")
    for i in 0 .. n
      for j in 0 .. 12
        custrecord[j] = x[i,j]
      end
      csv_string = FasterCSV.generate_line(custrecord)
        csv_string.chop!
        csv_string.gsub!(/,/, ';')
        op.puts csv_string
    end

The result in folder Test is: testmap.csv  -->  0Kb!!  (Type CSV file)

It seems a very simple program which should work.

Can anyone tell me what's wrong?

Thanks in advance,

Thiel
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2009-02-11 15:36
thiel wrote:
> This is the code:

Only part of it - you haven't shown what sort of object custrecord is,
for example.

> op = File.new("C:/Test/testmap.csv", "w")
>     for i in 0 .. n
>       for j in 0 .. 12
>         custrecord[j] = x[i,j]
>       end

STDERR.puts "custrecord = #{custrecord.inspect}"

>       csv_string = FasterCSV.generate_line(custrecord)
>         csv_string.chop!
>         csv_string.gsub!(/,/, ';')
>         op.puts csv_string
>     end
>
> The result in folder Test is: testmap.csv  -->  0Kb!!  (Type CSV file)

That STDERR line will tell you whether custrecord contains what you
expect. If not, work backwards until you find the problem (e.g. look at
what's in x)

There are simpler ways to drive fastercsv than your code though. Try
this:

require 'rubygems'
require 'fastercsv'
FasterCSV.open("/tmp/test.csv", "w", :col_sep=>";") do |csv|
  custrecord = ["foo","bar","baz"]
  csv << custrecord
end

The documentation for fastercsv is within the code, which may be
installed somewhere like .../gems/fastercsv-1.4.0/lib/faster_csv.rb on
your system.

Or type "gem server --daemon" then point your web browser at
http://localhost:8808/
54ee59d05d2b1bf0dd8c644ea586df00?d=identicon&s=25 thiel (Guest)
on 2009-02-11 17:22
(Received via mailing list)
Hi Brian,

Many thanks for your suggestion to use the inspect method. That revealed
a 'beginners' program error. :-D
After having made the correction I applied your solution, and it made
the code simpler. And what's more important: It works!

Here is the code snippet:

FasterCSV.open("c:/Test/test.csv", "w", :col_sep=>";") do |csv|

      for i in 0 .. n
        for j in 0 .. 12
          klantrecord[j] = x[i,j]
        end
        csv << klantrecord
       end
    end

Best regards,

Thiel


Brian Candler schreef:
This topic is locked and can not be replied to.