Weird backslash substitution in Ruby

前端 未结 5 1611
时光说笑
时光说笑 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 10:07

    the pickaxe book mentions this exact problem, actually. here's another alternative (from page 130 of the latest edition)

    str = 'a\b\c'               # => "a\b\c"
    str.gsub(/\\/) { '\\\\' }   # => "a\\b\\c"
    

提交回复
热议问题