Last Updated: September 09, 2019
· eallam

Easily change parts of a URI

I ran into a situation the other day when I had a URI string and I wanted to change it from http to https. Luckily the Ruby Standard Library has a module called URI that allows you to do pretty much anything you'd need to with a URI string. For example, to make sure a URI is https, you just have to do:

> require 'uri'
> uri_string = ""
> uri = URI(uri_string)
> uri.scheme = 'https'
> uri.to_s
=> ""

You can also use URI to read out the different parts of the URI, like so:

> require 'uri'
> uri_string = ""
> uri = URI uri_string
> uri.scheme
=> "http"
> uri.path
=> "/users/1"
=> ""
> uri.query
=> "name=eric"

Then, if you want to parse that uri.query string into a Hash, you can use another Standard Library method CGI.parse:

> require 'cgi'
> CGI.parse uri.query
=> {"name"=>["eric"]}