Ruby 字符串前加 '\' 字符 [英] Ruby string prepend '\' character
问题描述
当我尝试在代码下方运行时,为什么 ruby 在前面加上 '\' 字符.它只发生在 '#$'
why ruby is prepends '\' character while I am trying to run below code. It is happening with only '#$'
所有 ruby 版本都会发生这种情况.
It is happening with all ruby version.
puts '#$' => '\#$'
或
'#$' => '\#$'
或
'mypassord#$123' => 'mypassord\#$123'
请在这里分享您的经验.是红宝石问题还是什么?
Please share you experience here. Is it a ruby problem or anything?
推荐答案
不,这不是 ruby 问题.这是你的问题.由于#$foo
可以解释为全局变量$foo
的插值,因此需要对#
字符进行转义.这就是为什么有一个反斜杠.
No it is not a ruby problem. It is your problem. Since #$foo
can be interpreted as interpolation of the global variable $foo
, it is necessary to escape the #
character. That is why there is a backslash.
更准确地说,不可能用字符串 "#$"
($
是一个无效的全局变量) 或 "#$123 进行插值"
($123
是一个无效的全局变量),但它使检查算法或插值算法变得复杂,以检查 #$
之后的序列,所以我猜这就是为什么即使在这种情况下 #
也会被转义.
To be more precise, there is no possibility of interpolation with the string "#$"
($
is an invalid global variable) or "#$123"
($123
is an invalid global variable), but it makes the inspection algorithm or the interpolation algorithm complicated to check the sequence after #$
, so I guess that is why #
is escaped even in such cases.
这篇关于Ruby 字符串前加 '\' 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!