Weird backslash substitution in Ruby

前端 未结 5 1619
时光说笑
时光说笑 2020-11-28 09:19

I don\'t understand this Ruby code:

>> puts \'\\\\ <- single backslash\'
# \\ <- single backslash

>> puts \'\\\\ <- 2x a, because 2 bac         


        
5条回答
  •  心在旅途
    2020-11-28 09:45

    Clearing up a little confusion on the author's second line of code.

    You said:

    >> puts '\\ <- 2x a, because 2 backslashes get replaced'.sub(/\\/, 'aa')
    # aa <- 2x a, because two backslashes get replaced
    

    2 backslashes aren't getting replaced here. You're replacing 1 escaped backslash with two a's ('aa'). That is, if you used .sub(/\\/, 'a'), you would only see one 'a'

    '\\'.sub(/\\/, 'anything') #=> anything
    

提交回复
热议问题