To gsub / to "" ruby
I tried as,
ss = "http://url.com/?code=\#{code}"
I am fetching this url from database then have to gsub \\ to '' to pass the dynamic value in code
How to gsub \\ to ''
required output
ss = "http://url.com/?code=#{code}"
Your problem is actually not a problem. When you write "http://url.com/?code=\\#{code}"
in ruby, \\#
means that ruby is escaping the #
character, cause #
is a protected character. So you should have the backslash to escape it.
Just to prove this, if you write in a console your string with single quotes (single quotes will escape any special character (but single quotes, of course)):
>> 'http://url.com/?code=#{code}'
=> "http://url.com/?code=\#{code}"
This may be a little obscure but, if you want to evaluate the parameter code in the string, you could do something like this:
>> code = 'my_code'
>> eval("\"http://url.com/?code=\#{code}\"")
=> "http://url.com/?code=my_code"
I believe what you may be asking is "how do I force Ruby to evaluate string interpolation when the interpolation pattern has been escaped?" In that case, you can do this:
eval("\"#{ss}\"")
If this is what you are attempting to do, though, I would highly discourage you. You should not store strings containing the literal characters #{ }
in your database fields. Instead, use %s
and then sprintf
the values into them:
# Stored db value
ss = "http://url.com/?code=%s"
# Replace `%s` with value of `code` variable
result = sprintf(ss, code)
If you only need to know how to remove \\
from your string, though, you can represent a \\
in a String or Regexp literal by escaping it with another \\
.
ss.gsub(/\\/,'')
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.