9

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?

Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
bob
  • 93
  • 1
  • 3

2 Answers2

19
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

Michaël Witrant
  • 7,525
  • 40
  • 44
  • Worthing pointing out that there is no error checking. Problems can occur with both the URI and the local disk open calls. For simple scripts it might not be a problem. For anything that needs long term reliability you'll want to add some safety nets. – Alan W. Smith Jun 04 '15 at 14:39
  • Where does this file get saved to? – Ka Mok Sep 06 '16 at 21:45
  • In the file `file_to_write` in the current directory of the process. You can provide a full path instead. – Michaël Witrant Sep 09 '16 at 08:58
0

The pickaxe to the rescue. (this used to be a good page, but is no longer working)

Try this instead: Open an IO stream from a local file or url

Community
  • 1
  • 1
Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43