Reputation: 7533
In Ruby I am trying to replace double backslash \\
with single backslash \
in string but it's not working.
This is my string
line = "this\\is\\line"
desired output
"this\is\line'
This is what i tried
line.gsub("\\", "\") # didn't work
line.gsub("\\", "/\") # didn't work
line.gsub("\\", '\') # didn't work with single quote as well
line.gsub("\\", '/\') # din't work with single quote as well
Upvotes: 0
Views: 119
Reputation: 12356
You are being tricked - it actually is working, but the console is displaying it escaped with \ in line. Use puts
to actually see what it is being set without it being escaped with backslashes.
So #1: line = "this\\is\\line"
is actually this\is\line
. Proof:
irb(main):015:0> line = "this\\is\\line"
=> "this\\is\\line"
irb(main):016:0> puts line
this\is\line
So to actually make a string with double backslashes, you need: line = "this\\\\is\\\\line"
. Proof:
irb(main):017:0> line = "this\\\\is\\\\line"
=> "this\\\\is\\\\line"
irb(main):018:0> puts line
this\\is\\line
So finally, once you actually have a string with double backslashes, this is the gsub you want: line.gsub("\\\\", "\\")
irb(main):020:0> line = "this\\\\is\\\\line"
=> "this\\\\is\\\\line"
irb(main):021:0> puts line.gsub("\\\\", "\\")
this\is\line
Upvotes: 3