Ruby URI Percent Encoding

CGI.escape and URI.escape are both available in the standard Ruby libraries for URL encoding. But which one should you use?

Here's a quick note about the differences:

irb(main):001:0> require 'cgi'
=> true
irb(main):002:0> require 'uri'
=> true
irb(main):003:0> URI.escape('Test Hi<>?/&;=:')
=> "Test%20Hi%3C%3E?/&;=:"
irb(main):004:0> URI.escape('Test Hi<>?/&;=:', '&')
=> "Test Hi<>?/%26;=:"
irb(main):005:0> CGI.escape('Test Hi<>?/&;=:')
=> "Test+Hi%3C%3E%3F%2F%26%3B%3D%3A"

Note that URI.escape fails to encode the ampersand... So definitely use CGI.escape if you want to safely encode a query parameter for net/http calls.