Encoding special characters in URLs with Ruby I have the following Ruby code snippet:

  url = "http://somewiki.com/index.php?book=#{author}:#{title}&amp;action=edit"
  encoded = URI.encode(url)
  encoded.gsub(/&amp;/, "%26").sub(/%26action/, "&amp;action")


The last line is needed since I have to encode the ampersands (&amp;) in the author and title but I need to leave the last one (&amp;action...) intact.

Consider this example for clarity:

author = "John &amp; Diane"
title = "Our Life &amp; Work"
url = "http://somewiki.com/index.php?book=#{author}:#{title}&amp;action=edit"
encoded = URI.encode(url)
encoded.gsub(/&amp;/, "%26").sub(/%26action/, "&amp;action")

# =&gt; "http://somewiki.com/index.php?book=John%20%26%20Diane:Our%20Life%20%26%20Work&amp;action=edit" 


Although this result is satisfactory, I'd like to clean the original code with the gsub/sub calls. Any ideas?

PS: I could "clean" both params before passing them to the url = ... line but then the % characters will be re-encoded as %25 by the URI.encode call so I don't think that's an option. I'd love to be proved wrong here though.
Unless you need the unencoded url (for logging?), I would just:

encoded_url = "http://somewiki.com/index.php?book=#{CGI.escape(author)}:#{CGI.escape(title)}&amp;action=edit"