我不理解这段Ruby代码:
>> puts '\\ <- single backslash'
# \ <- single backslash
>> puts '\\ <- 2x a, because 2 backslashes get replaced'.sub(/\\/, 'aa')
# aa <- 2x a, because two backslashes get replaced
到目前为止,一切都符合预期。但是如果我们使用/ \ / \ / 搜索1,并用
'\\\\'
编码的2替换,为什么会得到这个:
<code>>> puts '\\ <- only 1 ... replace 1 with 2'.sub(/\\/, '\\\\')
# \ <- only 1 backslash, even though we replace 1 with 2
</code>
然后,当我们使用
'\\\\\\'
对3进行编码时,我们只得到2:
<code>>> puts '\\ <- only 2 ... 1 with 3'.sub(/\\/, '\\\\\\')
# \\ <- 2 backslashes, even though we replace 1 with 3
</code>
有人能理解为什么反斜杠会在替换字符串中被吞掉吗?这种情况在1.8和1.9上都会发生。