Kevin Jalbert Kevin Jalbert - 3 months ago 7
Ruby Question

Ruby replace double backslash with single backslash

I cannot seem to replace a double backslash with a single backslash in Ruby. I figured I would just escape the backslashes with another backslash.

1.9.3-p194 :001 > line = "this\\is\\a\\test"
=> "this\\is\\a\\test"
1.9.3-p194 :002 > line.gsub("\\\\", "\\") # Nothing
=> "this\\is\\a\\test"

That didn't work so I decided to try and find a match that at least makes a replacement.

1.9.3-p194 :003 > line.gsub("\\", "_") # This works for replacing \\
=> "this_is_a_test"
1.9.3-p194 :004 > line.gsub("\\", "\\") # Nothing
=> "this\\is\\a\\test"

I still cannot find an easy way to do this in Ruby.


With this line...

line = "this\\is\\a\\test"

... you actually create a string looking like this:


... as each \\ will be recognized as a single slash. Of course, you won't be able to replace double slashes, as there's none in your string.

line.gsub("\\", "_") line is doing just that: replacing all the single slashes in your string with _ symbol.

line.gsub("\\", "\\") is just a no-op in disguise.