write a file

L

Li Chen

Hi all,

I use the following script to write a 2D array. I wonder if there is
improvement for them.

Thanks,

Li

############script##########
data_all=[
(1..10).to_a,
(1..10).to_a,
(1..10).to_a,
(1..10).to_a
]# a 2D array


File.open('test3.txt','w') do |a_f|
data_all.each do |row |
row.each {|e| a_f.print e ; a_f.print "\t"}
a_f.puts
end

end
 
R

Rodrigo Bermejo

Li said:
Hi all,

I use the following script to write a 2D array. I wonder if there is
improvement for them.

Thanks,

Li

############script##########
data_all=[
(1..10).to_a,
(1..10).to_a,
(1..10).to_a,
(1..10).to_a
]# a 2D array


File.open('test3.txt','w') do |a_f|
data_all.each do |row |
row.each {|e| a_f.print e ; a_f.print "\t"}
a_f.puts
end

end

What you have is good enough.
There are a few things which could be better, for example formatting
(sprintf), and error reporting, also what I would do is to encapsulate
this code into a function so that you can re use it later on.

def array2D_to_file(array2D,file_name)
...
..
end

my 2 cents
 
L

Li Chen

Rodrigo said:
What you have is good enough.
There are a few things which could be better, for example formatting
(sprintf), and error reporting, also what I would do is to encapsulate
this code into a function so that you can re use it later on.

def array2D_to_file(array2D,file_name)
...
..
end

my 2 cents

Unfortunately Excel doesn't see the formatted outputs correctly, so I
don't perform the formatting.

Li
 
D

Daniel Danopia

data_all=[
        (1..10).to_a,
        (1..10).to_a,
        (1..10).to_a,
         (1..10).to_a
         ]# a 2D array

File.open('test3.txt','w') do |a_f|
       data_all.each do |row |
              row.each {|e| a_f.print e ;   a_f.print "\t"}
              a_f.puts
       end

end

I would do something more along the lines of this:

File.open('test.txt', 'w') do |file|
data_all.each do |row|
file.puts row.join("\t")
end
end

you may want to look at fastercsv.

kind regards -botp

This is tab-separated, but if Excel is the ultimate goal, I guess that
CSV would work. Fortunately, I don't use Excel, so I don't know much
along those lines.
 
L

Li Chen

Thairuby said:
#I try to shorten it

File.open('test3.txt','w') do |a_f|
a_f.print data_all.map{|row| row.join("\t")}.join("\n")
end

#but for Excel, csv file is better

File.open('test3.csv','w') do |a_f|
a_f.print data_all.map{|row| row.join(",")}.join("\n")
end

Thank you very much for the code. But I still like to do the format
after file
is read by Excel.

Li
 

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,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top