how to print/write the result to a file

L

Li Chen

Hi folks,

Assume I have an array=[1,2,3]

How do I print/write the result to a file called test.text either in the
same folder or in a different folder?

Thanks in advance,

Li
 
J

Jan Svitok

Hi folks,

Assume I have an array=[1,2,3]

How do I print/write the result to a file called test.text either in the
same folder or in a different folder?

Thanks in advance,

Li

It depends on the format you want, e.g.

File.open('path/to/test.txt', 'w') do |f|
f.write(array.join(', '))
end

1. you can use forward slashes (/) even on windows
2. instead of f.write you could use f.puts, f.print, etc.
3. another version is:

f = File.open(',...', 'w')
f.puts ...
f.close

The block version is safer than this as it closes the file
automatically, even in the case of exception within the block.
 

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,776
Messages
2,569,603
Members
45,190
Latest member
Martindap

Latest Threads

Top