If I run a simple script using OpenURI, I can access a web page. The results get written to the terminal.
Normally I would use bash redirection to write the results to a file.
How do I use ruby to write the results of an OpenURI call to a file?
It is a way of processing a file such as creating a new file, reading content in a file, writing content to a file, appending content to a file, renaming the file and deleting the file. Common modes for File Handling. “r” : Read-only mode for a file. “r+” : Read-Write mode for a file.
Ruby allows the following open modes: "r" Read-only, starts at beginning of file (default mode). "r+" Read-write, starts at beginning of file. "w" Write-only, truncates existing file to zero length or creates a new file for writing.
Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.
require 'open-uri'
open("file_to_write.html", "wb") do |file|
URI.open("http://www.example.com/") do |uri|
file.write(uri.read)
end
end
Note: In Ruby < 2.5 you must use open(url)
instead of URI.open(url)
. See https://bugs.ruby-lang.org/issues/15893
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With