views:

600

answers:

3

In Ruby, I have:

require 'uri'
foo = "et tu, brutus?"
bar = URI.encode(foo)      # => "et%20tu,%20brutus?"

I'm trying to get bar to equal "et%20tu,%20brutus%3f" ("?" replaced with "%3F") When I try to add this:

bar["?"] = "%3f"

the "?" matches everything, and I get

=> "%3f"

I've tried

bar["\?"]
bar['?']
bar["/[?]"]
bar["/[\?]"]

And a few other things, none of which work.

Hints?

Thanks!

+2  A: 
Geo
Thanks. This and CGI.escape both work nicely. I went with this one, though. (Fewer requires.)
Olie
@geo, although your answer is technically correct and to Olie's point, he should really use CGI.escape.
vladr
Yes, but this way his knowledge of the language increases.
Geo
+8  A: 

require 'cgi' and call CGI.escape

kmkaplan
+1  A: 

There is only one good way to do this right now in Ruby:

require "addressable/uri"
Addressable::URI.encode_component(
  "et tu, brutus?",
  Addressable::URI::CharacterClasses::PATH
)
# => "et%20tu,%20brutus%3F"

But if you're doing stuff with URIs you should really be using Addressable anyways.

sudo gem install addressable
Bob Aman