"Sven Schott" <sven_schott / compnow.com.au> schrieb im Newsbeitrag
news:CBD4166F-BE86-11D8-B72B-000A9571732E / compnow.com.au...
> I was actually just about to ask that. This was how I did it(pretty
> much the same way as yours).
>
> file = File.open("file.csv", "r")
> arr =[]
> file.each { |i| arr << i.chomp.split(/\t/) }

This can be nicely done with a one liner:

arr = File.open("file.csv") {|io| io.inject([]) {|a, line| a <<
line.chomp.split(/\t/)} }

which has the added value of closing the file properly.

> if you want to output it nicely you can do something like
>
> puts arr.each { |a| puts a.join("\t").to_s + "\n" }
>
> Or to a file
>
> savefile = File.new("file2.csv", "w")
> arr.each { |a| savefile << arr.join("\t").to_s + "\n" }

File.open("file2.csv", "w") do |savefile|
  arr.each { |a| savefile.puts arr.join("\t") }
end

> Just my 2c. I think I did it well 'cause I worked on it for a while. I
> love blocks.

Then you should get used to the habit to use them with File.open() - that
way you ensure that file handles are closed properly. :-)

Kind regards

    robert


>
> Sven
>
>
> On 14/06/2004, at 9:43 AM, Todd Gardner wrote:
>
> > Actually this is a tab delimited file, here is the .csv.
> >
> > 6/10/2004,-44.87,4INKJETS.COM 888-321-2552 CA
> > 6/8/2004,-107.26,SAFEWAY STORE00014837 SAN JOSE CA
> > 6/7/2004,-24.95,DR *REGSOFT.COM Regsoft.com GA
> > 6/3/2004,114.96,ONLINE PAYMENT
> > 5/28/2004,214.99,ONLINE PAYMENT
> > 5/27/2004,-114.96,SAFEWAY STORE00014837 SAN JOSE CA
> > 5/24/2004,-214.99,NEWEGG COMPUTERS 800-390-1119 CA
> > 3/9/2004,-40,TQ PHONE ADVANCE - CA
> >
> > How can I do this more elegantly?
> >
> > ary = []
> > fi = File.open("test1.csv","r")
> > fo = File.open("test1.out","w")
> > fi.each { |line|
> >         a = line.strip.split(',')
> >         ary << a
> > fo.puts line
> > }
> > #~ # test print-out of one arrayrow
> > i=0
> > 1.times do
> >   puts ary[i]
> >   i+=1
> > end
> >
> > fi.close
> > fo.close
> >
> > Thanks again for listening to the newbie question!
> >
> > Todd
> >
>
>
>