gsub - Replacing `\` with `\\` in ruby -
i'm trying replace occurrences of \ \\. here first try:
> puts '\\'.gsub('\\', '\\\\') \ i pretty surprised when saw output. after experimenting able wanted this code:
> puts '\\'.gsub('\\', '\\\\\\') \\ why isn't first piece of code working? why need 6 backslashes?
'\\'.gsub('\\', '\\\\') when substitution occurs, substitution string '\\\\' passed regexp engine, , \\ replaced \. substitution string ends '\\', single backslash.
the idomatic way replace single bachslach double use:
str.gsub(/\\/, '\\\\\\\\\') # 8 backslashes!
Comments
Post a Comment