简体   繁体   中英

In Ruby, how do I replace the question mark character in a string?

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.

require 'cgi'并调用CGI.escape

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}]/, '')

URI.escape accepts the optional parameter to tell which characters you want to escape. It overrides defaults so you'll have to call it twice.

> URI.escape URI.escape("et tu, brutus?"), "?"
=> "et%20tu,%20brutus%3F"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM