I'm learning Ruby, and can't figure out how to open and write to a local file. How can I open a file and write a string to it?
Asked
Active
Viewed 241 times
0
-
It would be really good if you spent time reading through [the core and standard Ruby libraries](http://www.ruby-doc.org/) to familiarize yourself with what's available. Even if you don't know what everything is used for, over time you'll run into the need, and, having glanced at the documentation a few times, you'll remember it's in there somewhere. As is, your question is very elementary, and very well explained by the [IO classes' documentation](http://www.ruby-doc.org/core-2.0.0/IO.html). – the Tin Man Oct 16 '13 at 04:26
4 Answers
1
Opening and writing to a file is done via Ruby's File class. Here's an example.
File.open('path/to/file.txt', 'w') do |file|
file.write('this is how you write to a file')
end
The first argument to File#open
is the relative file location. The second is the mode.

Chris Cashwell
- 22,308
- 13
- 63
- 94
-
Don't forget to close the file, `file.close`, after you're done writing to it. – HM1 Oct 15 '13 at 22:27
-
2
-
1
0
To read from file
File.read(file)
To write string
to file
File.write(file, string)

sawa
- 165,429
- 45
- 277
- 381
-
1@DavidLjungMadison, you probably should read the [IO class documentation](http://www.ruby-doc.org/core-2.0.0/IO.html) a bit more closely. @sawa's answer is correct as File inherits from IO, which has both class and instance versions of `read` and `write`. – the Tin Man Oct 16 '13 at 04:31
-
@DavidLjungMadison Don't tell a lie. It was not added in Ruby 2.0. It is available at least in Ruby 1.9.3. Don't make an un-useful excuse. – sawa Oct 17 '13 at 06:33
-
@DavidLjungMadison Doesn't it even come to your mind to remove your first comment that is telling false information? Really surprising. All you think of is thinking what another layer of excuse to add? – sawa Oct 18 '13 at 09:47
-1
What exactly do you want? Do you want to download the photo and save it? Or do you want to save the URL of the photo?
You can save the photo with Mechanize
, because Mechanize.new.get
creates a new file retrieved from the given URL and response body.
file = Mechanize.new.get(url)
file.class #=> Is a file, returns Mechanize::File
file.save('photo.jpg')
You can name the file however you like, with the #save
method.
Or you can save the URL of the photo in a file by using the Ruby File class.
File.open('photo_url.txt', 'w') { |file| file.write(url) }
The file will be automatically closed by Ruby after the block terminates.

the Tin Man
- 158,662
- 42
- 215
- 303

JanDintel
- 999
- 7
- 11
-
There's nothing in the question hinting that the OP wants to retrieve an image from a URL. – the Tin Man Oct 16 '13 at 04:34
-
-1
one liner
File.open(path, "w") {|f| f.write(string)}

SheetJS
- 22,470
- 12
- 65
- 75

boulder_ruby
- 38,457
- 9
- 79
- 100