7 Ways to Encode URLs in Ruby

Rainer Borene
1 min readDec 6, 2018

--

If you are familiar with Ruby standard library then you probably know these two methods: URI.escape and CGI.escape. But turns out they are slight different and conforms to different specifications. Let’s see what are the key differences between them.

URI.escape method follows RFC 2396 also know as “Uniform Resource Identifiers(URI): Generic Syntax”. Some developers have some trouble using this escaping method.

I won’t go into the details of each specification but the TLDR; is that it doesn’t cover some characters. In other words, this method does not produce the same results of the encode URI JavaScript function.

If you need to encode query strings then CGI.escape method is probably what you’re looking for. CGI.escape follows the CGI/HTML forms spec and returns a string like application/x-www-form-urlencoded requests, which requires spaces to be escaped to + and encode most special characters.

But there is another encoding method available on the Ruby standard library. ERB::Util.url_encode follows RFC 3986, which requires spaces to be encoded to %20 which is the main difference from the previous approach.

Here’s a list of all URL encoding/decoding methods available on the Ruby
standard library. Don’t take my word for it and test for yourself.

ERB::Util.url_encode
URI.escape # alias to URI.encode
URI.unescape # alias to URI.decode
URI.encode_www_form_component
URI.decode_www_form_component
CGI.escape
CGI.unescape

--

--