Replace each occurance of forward slash in ruby string

Sergio

New Member
#1
I have a string that has the following structure:
Mã:
/base/6/value/6/start
I want to escape each forward slash with a backward slash, to receive the following:
Mã:
\/base\/6\/value\/6\/start
I expected this to work with string.gsub('/', '\/), but that adds double backslashes, what am I doing wrong?
 

Admin

Administrator
Thành viên BQT
#2
what am I doing wrong?
Misinterpreting what you see. There are no "double backslashes" in the string. That's how single backslashes are displayed (in IRB and other places that use #inspect for displaying things)

Try this instead (puts will not additionally escape backslashes or other chars)
Mã:
 puts string.gsub('/', '\/')
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top