r3b00t
r3b00t

Reputation: 7533

Ruby replace double blackslash with single blackslash

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

Answers (1)

PressingOnAlways
PressingOnAlways

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

Related Questions