Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape double and single backslashes in a string in Ruby

I'm trying to access a network path in my ruby script on a windows platform in a format like this.

\\servername\some windows share\folder 1\folder2\

Now If I try to use this as a path, it won't work. Single backslashes are not properly escaped for this script.

path = "\\servername\some windows share\folder 1\folder2\"
d = Dir.new(path)

I tried everything I could think of to properly escape slashes in the path. However I can't escape that single backslash - because of it's special meaning. I tried single quotes, double quotes, escaping backslash itself, using alternate quotes such as %Q{} or %q{}, using ascii to char conversion. Nothing works in a sense that I'm not doing it right. :-) Right now the temp solution is to Map a network drive N:\ pointing to that path and access it that way, but that not a solution.

Does anyone have any idea how to properly escape single backslashes?

Thank you

like image 964
konung Avatar asked May 05 '10 15:05

konung


People also ask

How do you add a backslash to a string in Ruby?

So if you enter "\\", it's going to display "\\" event though it's a string with a single backslash in it. To discover what's truly in the string, you should use puts. For example, puts "\\" will display a single backslash.


1 Answers

Just double-up every backslash, like so:

"\\\\servername\\some windows share\\folder 1\\folder2\\"
like image 89
John Douthat Avatar answered Sep 29 '22 02:09

John Douthat