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"}
v
In this Ruby version:
We use the built-in
URI
module to parse URLs.The
URI.parse
method is used to parse the URL string into aURI
object.We can access various components of the URL directly through methods on the
URI
object, such asscheme
,host
,path
, etc.For user information, we manually split the
user
string to get username and password separately.The
host
method returns both hostname and port, whilehostname
andport
methods return these components separately.Query parameters are accessed via the
query
method, which returns the raw query string.To parse the query string into a hash, we use
URI.decode_www_form
and 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.