简体   繁体   English

如何在红宝石中将斜杠(/)换成“”

[英]How to gsub slash (/) to “” in ruby

To gsub / to "" ruby gsub /“红宝石”

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 我正在从数据库中获取此url,然后必须gsub \\到''以在代码中传递动态值

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. 当您在ruby中编写"http://url.com/?code=\\#{code}"时, \\#表示ruby在转义#字符,因为#是受保护的字符。 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?" 我相信您可能会问:“当插值模式已转义时,如何强制Ruby评估字符串插值?” 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: 而是使用%s ,然后将值sprintf放入其中:

# 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 \\ . 但是,如果只需要知道如何从字符串中删除\\ ,则可以在String或Regexp文字中表示一个\\ ,方法是用另一个\\进行转义。

ss.gsub(/\\/,'')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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