# How to print/write the result to a file

**URL:** <https://www.ruby-forum.com/t/how-to-print-write-the-result-to-a-file/72949>\
**Category:** Ruby\
**Created:** [October 20, 2006, 1:19am UTC](https://www.ruby-forum.com/t/how-to-print-write-the-result-to-a-file/72949 "2006-10-20T01:19:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [October 20, 2006, 1:19am UTC](https://www.ruby-forum.com/t/how-to-print-write-the-result-to-a-file/72949/1 "2006-10-20T01:19:07Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [October 20, 2006, 1:32am UTC](https://www.ruby-forum.com/t/how-to-print-write-the-result-to-a-file/72949/2 "2006-10-20T01:32:06Z")

</div>

On 10/20/06, Li Chen [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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.
