How to Parse a URL in Ruby?

Parsing a URL in Ruby is a breeze with the URI module. Here's a step-by-step guide on how to do it:

  1. Requiring the URI Module
require 'uri'
  1. Creating a URI Object
url = URI.parse("https://example.com/path?name=value#hash")
  1. Accessing URL Components
puts url.scheme   # Output: https
puts url.host     # Output: example.com
puts url.path     # Output: /path
puts url.query    # Output: name=value
puts url.fragment # Output: hash
  1. Working with URL Parameters
# Get a hash of URL parameters
params = URI.decode_www_form(url.query).to_h
puts params  # Output: {"name"=>"value"}
  1. Modifying and Reconstructing URLs
# Create a new URL with modified components
new_url = URI::HTTP.build({host: url.host, path: "/newpath", query: url.query, fragment: url.fragment})
puts new_url  # Output: https://example.com/newpath?name=value#hash

With the URI module, parsing a URL in Ruby is straightforward, enabling you to access, analyze, and modify URLs with ease.

Lastly, if you want to grab query parameters from any url without using ruby, use parseurlonline.com to quickly get the data without any hassle.