Retrieve contents of URL as string Retrieve contents of URL as string ruby ruby

Retrieve contents of URL as string


You can do the same without OpenURI:

require 'net/http'require 'uri'def open(url)  Net::HTTP.get(URI.parse(url))endpage_content = open('http://www.google.com')puts page_content

Or, more succinctly:

Net::HTTP.get(URI.parse('http://www.google.com'))


The open method passes an IO representation of the resource to your block when it yields. You can read from it using the IO#read method

open([mode [, perm]] [, options]) [{|io| ... }] open(path) { |io| data = io.read }


require 'open-uri'open(url) do |f|  page_string = f.readend

See also the documentation of IO class