title: How do I parse an encoded URI in Ruby?
body: <p>I'm trying to parse a URI that has brackets - [ and ] - in it. I have tried to parse this directly with URI.parse but the brackets cause this to fail. I therefore tried to encode the URI with CGI::escape which takes care of the brackets but when I try to parse this encoded URI with URI.parse it doesn't seem to recognise it as a URI and puts the entire URI into the path object.</p>
  
  <p>To demonstrate in an irb session;</p>
  
  <pre><code>irb(main):001:0&gt; require 'uri'
  =&gt; true
  irb(main):002:0&gt; require 'cgi'
  =&gt; true
  irb(main):003:0&gt; name = "http://www.website.com/dir1/dir[2]/file.txt"
  =&gt; "http://www.website.com/dir1/dir[2]/file.txt"
  irb(main):004:0&gt; encoded_name = CGI::escape(name)
  =&gt; "http%3A%2F%2Fwww.website.com%2Fdir1%2Fdir%5B2%5D%2Ffile.txt"
  irb(main):005:0&gt; parsed_name = URI.parse(encoded_name)
  =&gt; #&lt;URI::Generic:0x00000001e8f520 URL:http%3A%2F%2Fwww.website.com%2Fdir1%2Fdir%5B2%5D%2Ffile.txt&gt;
  irb(main):006:0&gt; parsed_name.scheme
  =&gt; nil
  irb(main):007:0&gt; parsed_name.host
  =&gt; nil
  irb(main):008:0&gt; parsed_name.path
  =&gt; "http%3A%2F%2Fwww.website.com%2Fdir1%2Fdir%5B2%5D%2Ffile.txt"
  irb(main):009:0&gt; URI.split(encoded_name)
  =&gt; [nil, nil, nil, nil, nil, "http%3A%2F%2Fwww.website.com%2Fdir1%2Fdir%5B2%5D%2Ffile.txt", nil, nil, nil]
  </code></pre>
  
  <p>Anyway, my work around at the moment is the following ugly, but effective, hack</p>
  
  <pre><code>encoded_name = name.gsub(/\[/,"%5B").gsub(/\]/,"%5D")
  </code></pre>
  
  <p>Parsing this with URI.parse produces the desired result but won't cope if other strange characters find their way into my URIs. So my question is, is there a solid way of doing this that won't fall down?</p>