Escape double and single backslashes in a string in Ruby
Just double-up every backslash, like so:
"\\\\servername\\some windows share\\folder 1\\folder2\\"
Try this
puts '\\\\servername\some windows share\folder 1\folder2\\'#=> \\servername\some windows share\folder 1\folder2\
So long as you're using single quotes to define your string(e.g., 'foo'
), a single \
does not need to be escaped. except in the following two cases
\\
works itself out to a single\
. So,\\\\
will give you the starting\\
you need.- The trailing
\
at the end of your path will tries to escape the closing quote so you need a\\
there as well.
Alternatively,
You could define an elegant helper for yourself. Instead of using the clunky \
path separators, you could use /
in conjunction with a method like this:
def windows_path(foo) foo.gsub('/', '\\')endputs windows_path '//servername/some windows share/folder 1/folder2/'#=> \\servername\some windows share\folder 1\folder2\
Sweet!