b a d p o p c o r n

Ruby URI Percent Encoding

Written by Ben on March 30, 2007 |

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.

Posted in Ruby


1 Comment »

  1. Not only did URI not encode the ampersand but it neglected the /. I noticed this same issue with strings like “3/4″ in a url.

    Comment by Phillip Novess — May 3, 2007 @ 8:39 pm

RSS feed for comments on this post. | TrackBack URI

Leave a comment

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .