Like gsub slash "/" with backslash and slash "\ /" in ruby

I am trying to change "/foo/bar/dir"to "\/foo\/bar\/dir"ruby gsub command.

I am testing it in irb, the result

x = "/foo/bar/dir"

x.gsub("/","\/")

=> "/foo/bar/dir"

x.gsub("/","\\/")

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

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


Source of problems:

I am trying to execute a "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"

run command result

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

I need only one backslash, for example

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

"run" is a command from Capistrano

my decision

use a single quote instead of a double quote like this

path = real_path.gsub("/",'\/') 
+3
source share
2 answers

Yes

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

, , .inspect, irb, - , , . puts, .

+2

:

x = "/foo/bar/dir"
x.gsub("/","\\/")
=> "\\/foo\\/bar\\/dir"

, , . x.gsub("/","\\/") "\/foo\/bar\/dir", irb inspect to_s.

:

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

istead

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

- / \/,

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

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

irb ( ).

File.join ()

: ? (1)

Edit2: "/" "/", ?

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

? (1)?

Edit3:

:

>> real_path = "/foo/bar/dir"
=> "/foo/bar/dir"
>> path = real_path.gsub("/", "\\/")
=> "\\/foo\\/bar\\/dir"
>> puts "sed 's/SHARE_PATH/#{path}/g' #{path}/config/sphinx.yml > #{path}/config/sphinx.tmp.yml"
sed 's/SHARE_PATH/\/foo\/bar\/dir/g' \/foo\/bar\/dir/config/sphinx.yml > \/foo\/bar\/dir/config/sphinx.tmp.yml
=> nil
>>

, ?

+8

Source: https://habr.com/ru/post/1733823/


All Articles