Uri
Uri

Reputation: 2346

How to capture a response from an HTTP GET request

This is what I came up with, but I feel that there's a better way. I've also heard that I shouldn't use open-uri.

require 'open-uri'

min = 1
max = 1000

str = open("http://www.random.org/integers/?num=#{min}&min=1&max=#{max}&col=1&base=10&format=plain&rnd=new").read

puts str.chomp.to_i

Upvotes: 0

Views: 528

Answers (2)

WarHog
WarHog

Reputation: 8710

It looks like normal way, but if you're interested in another option, take a look at this:

require 'net/http'

min = 1
max = 1000
address = "http://www.random.org/integers/?num=#{min}&min=1&max={#max}&col=1&base=10&format=plain&rnd=new"

url = URI.parse(address)
response = Net::HTTP.get_response(url)
puts response.body  # => 932

Upvotes: 2

tokland
tokland

Reputation: 67850

Your code is ok, but since you asked, I'd write it a bit differently:

require 'open-uri'

url_template = "http://www.random.org/integers/?num=%{min}&min=1&max=%{max}&col=1&base=10&format=plain&rnd=new"
random_number = open(url_template % {:min => 1, :max => 1000}).readline.to_i
#=> 42

Upvotes: 1

Related Questions