如何转义单引号字符串中的斜杠?
在 Ruby 1.8.6 (2007-09-24 patchlevel 111) 中:
str = '\&123'
puts "abc".gsub("b", str) => ab123c
puts "abc".gsub("b", "#{str}") => ab123c
puts "abc".gsub("b", str.to_s) => ab123c
puts "abc".gsub("b", '\&123') => ab123c
puts "abc".gsub("b", "\&123") => a&123c <--- This I want to achieve using temporary variable
如果我将 str = '\&123'
更改为 str = "\&123"
它工作正常,但我从 match
函数获取 str
,所以我无法在括号内手动指定它。有什么方法可以将 'string'
更改为 "string"
行为吗?
In Ruby 1.8.6 (2007-09-24 patchlevel 111):
str = '\&123'
puts "abc".gsub("b", str) => ab123c
puts "abc".gsub("b", "#{str}") => ab123c
puts "abc".gsub("b", str.to_s) => ab123c
puts "abc".gsub("b", '\&123') => ab123c
puts "abc".gsub("b", "\&123") => a&123c <--- This I want to achieve using temporary variable
If I change str = '\&123'
to str = "\&123"
it works fine, but I get str
from match
function, so I cannot specify it manually within parentheses. Is there any way to change the 'string'
to "string"
behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许有更简单的方法,但是下面的代码可以工作
maybe there is a simpler way, however the code below works
简单:
您可能还想看看此处。
Simple:
You may also want to take a look here.
@瓦伦丁
->我的意思是比赛中的 str 没有逐字记录。因此出现了另一个(更简单的)解决方案,我不知道......
"abc".gsub("b") { str } -> a\&123c
@Valentin
-> I meant that str from match was not taken verbatim. Thus another (simpler) solution appeared, that I was not aware of....
"abc".gsub("b") { str } -> a\&123c
只需删除反斜杠即可:
无需保护内部带有反斜杠的&符号
单引号字符串文字(与双引号字符串文字不同)。
Just remove the backslash:
There is no need to protect the ampersand with a backslash inside
single-quoted string literals (unlike double-quoted ones).