Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to file in Ruby?

Tags:

file-io

ruby

I need to read the data out of database and then save it in a text file.

How can I do that in Ruby? Is there any file management system in Ruby?

like image 512
ohana Avatar asked May 06 '10 01:05

ohana


People also ask

How do I add files to Ruby?

Ruby file FAQ: How do I append text to a file in Ruby? Solution: Appending text to a file with Ruby is similar to other languages: you open the file in "append" mode, write your data, and then close the file. Here's a quick example that demonstrates how to append "Hello, world" to a file named myfile.


2 Answers

Are you looking for the following?

File.open(yourfile, 'w') { |file| file.write("your text") } 
like image 64
Todd R Avatar answered Sep 19 '22 04:09

Todd R


You can use the short version:

File.write('/path/to/file', 'Some glorious content') 

It returns the length written; see ::write for more details and options.

To append to the file, if it already exists, use:

File.write('/path/to/file', 'Some glorious content', mode: 'a') 
like image 38
Sébastien Le Callonnec Avatar answered Sep 20 '22 04:09

Sébastien Le Callonnec