using a \ in gsub

B

brandon coleman

In IRB if I type the following:
"te/st".gsub('/','\')
into irb, IRB screws up.
but if I type
File.expand_path($0).gsub('/','\\')
I get te\\st. what gives?? how do I get ruby to come up with te\st?

what I am trying to do is this:
File.expand_path($0).gsub('/','\') because with ruby in windows it uses
a / instead of a \ for path names which is screwing my pathnames up..
any suggestions???
 
A

Austin Ziegler

In IRB if I type the following:
"te/st".gsub('/','\')
into irb, IRB screws up.
but if I type
File.expand_path($0).gsub('/','\\')
I get te\\st. what gives?? how do I get ruby to come up with te\st?

what I am trying to do is this:
File.expand_path($0).gsub('/','\') because with ruby in windows it uses
a / instead of a \ for path names which is screwing my pathnames up..
any suggestions???

File.expand_path($0).gsub(%r{/}) { "\\" }

-austin
 
B

brandon coleman

Austin said:
File.expand_path($0).gsub(%r{/}) { "\\" }

-austin

that would give me two c:\\ruby\\ whatever and if I remove a \ it still
gives me an error...
 
S

Stefan Lang

that would give me two c:\\ruby\\ whatever and if I remove a \ it
still gives me an error...

Are you testing this in irb? You should know
that \ is used as escape character inside of Ruby string
literals. Thus if you want an actual backslash in the string,
you have to escape it with another backslash.
irb prints a ruby string literal to stdout, thus you see a
double backslash for every actual backslash in the string.

Try:
puts File.expand_path($0).gsub(%r{/}, "\\")
to see the "real" contents of the resulting string.

BTW: The literal "\" gives an error because the backslash
before the second quote tells Ruby to include the quote
in the string instead of interpreting it as string delimiter.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top