Bank Bank - 1 year ago 121
Ruby Question

How to gsub slash "/" with back slash and slash "\/" in ruby

I try to modify

by ruby gsub command.

I test it in irb the result is

x = "/foo/bar/dir"


=> "/foo/bar/dir"


=> "\\/foo\\/bar\\/dir"

Is it possible to replace "/" with "/" by gsub ?

Source of problems:

I try to execute "string in command line" and "real_path" is my variable

real_path = "/home/me/www/idata"

path = real_path.gsub("/","\\/")

=> \\/home\\/me\\/www\\/idata

# But what I expect is \/home\/me\/www\/idata

run "sed 's/SHARE_PATH/#{path}/g' #{path}/config/sphinx.yml > #{path}/config/sphinx.tmp.yml"

result from "run" command is

"sh -c 'sed '\''s/SHARE_PATH/\\/home\\/me\\/www\\/idata\\/shared/g .... "

I need is only one back slash like

"sh -c 'sed '\''s/SHARE_PATH/\/home\/me\/www\/idata\/shared/g .... "

"run" is command from Capistrano

my solution is

use single quote instead of double quote like this

path = real_path.gsub("/",'\/')

Answer Source


irb(main):028:0> (t = x.gsub("/", "\\/")) && nil
=> nil
irb(main):029:0> t
=> "\\/foo\\/bar\\/dir"
irb(main):030:0> puts t
=> nil

Your first example actually did what you wanted, but the .inspect method that irb is using is escaping backslashes, so it looked like there were extras. If you had used puts you would have seen the real result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download