f8pjda
Last Updated: September 22, 2018
·
4.19K
· 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 = "http://codeschool.com"
> uri = URI(uri_string)
> uri.scheme = 'https'
> uri.to_s
=> "https://codeschool.com"

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

> require 'uri'
> uri_string = "http://codeschool.com/users/1?name=eric"
> uri = URI uri_string
> uri.scheme
=> "http"
> uri.path
=> "/users/1"
> uri.host
=> "codeschool.com"
> 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"]}