In Ruby, how do I replace the question mark character in a string?
-
23-08-2019 - |
Question
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!
Solution
require 'cgi'
and call CGI.escape
OTHER TIPS
Here's a sample irb session :
irb(main):001:0> x = "geo?"
=> "geo?"
irb(main):002:0> x.sub!("?","a")
=> "geoa"
irb(main):003:0>
However, sub will only replace the first character . If you want to replace all the question marks in a string , use the gsub method like this :
str.gsub!("?","replacement")
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
If you know which characters you accept, you can remove those that don't match.
accepted_chars = 'A-z0-9\s,'
foo = "et tu, brutus?"
bar = foo.gsub(/[^#{accepted_chars}]/, '')