Heads up: This description was created by AI and might not be 100% accurate.
response_code_2xx.rb
This Ruby code snippet demonstrates a function rc2xx?
that checks if a given URI returns an HTTP response code in the 2xx range (success). It uses the net/http
library to make an HTTP GET request to the provided URI. The function parses the URI, establishes an HTTP connection (handling HTTPS if necessary), sends the request, and returns true
if the response code is between 200 and 299 (inclusive), otherwise it returns false
. The example call rc2xx?("https://yumayx.github.io/")
successfully returns true
because the website responds with a 200 status code.
Ruby code snippet
require "net/http"
#=> true
def rc2xx?(uri)
url = URI.parse(uri)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
request = Net::HTTP::Get.new(url.path)
response = http.request(request)
response_code = response.code.to_i
response_code >= 200 && response_code < 300
end
#=> :rc2xx?
rc2xx?("https://yumayx.github.io/")
#=> true
Executed with Ruby 3.4.5
.