问题
I have path strings (windows) with backslashes from a given export source with the format
"path\to\something"
When i try to read that in ruby, it reads
\t
and
\s
as escape sequences. In the end i want to just a
File.join(my_unix_path, "path\to\something")
I know that
%q{"path\to\something"}
works but since i have the string inside a variable, i cant use it like that. Any ideas how to remove it or convert it to regular unix path?
回答1:
Don't bother using backslashes for paths with Ruby.
Like many other languages, Ruby is aware of the platform and will automagically transform the path slashes to the correct direction for the platform. That means you can ALWAYS use forward slashes in paths, and be done with it:
From the documentation for IO:
Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename “/gumby/ruby/test.rb” will be opened as “\gumby\ruby\test.rb”. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"c:\\gumby\\ruby\\test.rb"
Our examples here will use the Unix-style forward slashes; File::SEPARATOR can be used to get the platform-specific separator character.
As added information, the problem you're seeing with "path\to\something"
having an escaped \s
and \t
is because the string is in double-quotes. If it was in single-quotes the problem wouldn't occur, because back-slashes lose their magic then. See "Backslashes in Single quoted strings vs. Double quoted strings in Ruby?" for more information.
回答2:
If you really do have "path\to\something"
(which I doubt), then you already have tabs and spaces in that string. And if you really want "path\to\something"
(which I also doubt), then you don't have to do anything. You already have that.
If you actually have 'path\to\something'
(which I think is likely), then you do not have the backslashes interpreted as escape characters. And if you actually want 'path\to\something'
(which I think is likely), then you don't have to do anything. You already have that.
来源:https://stackoverflow.com/questions/14871693/single-backslash-inside-ruby-string