Url Parsing in Ruby
Here’s the translation of the Go URL parsing example to Ruby, formatted for Hugo:
require 'uri'
# We'll parse this example URL, which includes a
# scheme, authentication info, host, port, path,
# query params, and query fragment.
s = "postgres://user:pass@host.com:5432/path?k=v#f"
# Parse the URL and ensure there are no errors.
u = URI.parse(s)
# Accessing the scheme is straightforward.
puts u.scheme
# User info contains all authentication info; we can extract
# username and password individually.
puts u.user
puts u.user.split(':')[0]
puts u.user.split(':')[1]
# The host contains both the hostname and the port,
# if present. We can extract them separately.
puts u.host
puts u.hostname
puts u.port
# Here we extract the path and the fragment after
# the #.
puts u.path
puts u.fragment
# To get query params in a string of k=v format,
# use query. You can also parse query params
# into a hash.
puts u.query
m = URI.decode_www_form(u.query).to_h
puts m
puts m['k']Running our URL parsing program shows all the different pieces that we extracted.
$ ruby url_parsing.rb
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
{"k"=>"v"}
vIn this Ruby version:
We use the built-in
URImodule to parse URLs.The
URI.parsemethod is used to parse the URL string into aURIobject.We can access various components of the URL directly through methods on the
URIobject, such asscheme,host,path, etc.For user information, we manually split the
userstring to get username and password separately.The
hostmethod returns both hostname and port, whilehostnameandportmethods return these components separately.Query parameters are accessed via the
querymethod, which returns the raw query string.To parse the query string into a hash, we use
URI.decode_www_formand convert the result to a hash.
This Ruby code provides equivalent functionality to the original Go example, using Ruby’s standard library and idiomatic Ruby syntax.