我想编写一个适用于Windows和Linux的应用程序.但我有一个路径问题,因为Windows使用"\"而Linux使用"/".我可以解决这个问题.谢谢
rub*_*nce 19
在Ruby中,Linux或Windows中的路径没有区别./无论环境如何,路径都应该使用.因此,要在Windows中使用任何路径,请将所有路径替换\为/.File#join适用于Windows和Linux.例如,在Windows中:
Dir.pwd
=> "C/Documents and Settings/Users/prince"
File.open(Dir.pwd + "/Desktop/file.txt", "r")
=> #<File...>
File.open(File.join(Dir.pwd, "Desktop", "file.txt"), "r")
=> #<File...>
File.join(Dir.pwd, "Desktop", "file.txt")
=> "C/Documents and Settings/Users/prince/Desktop/file.txt"
Run Code Online (Sandbox Code Playgroud)
只要Ruby正在开展工作,/路径名在Windows上就可以了
一旦你必须发送一个其他程序的路径,特别是在命令行或浏览器中的文件上传之类的东西,你必须在Windows中运行时将斜杠转换为反斜杠.
C:/projects/a_project/some_file.rb'.gsub('/', '\\')有魅力.(这应该是一个双重反斜杠 - 这个编辑器甚至用单引号看它也是一种逃避.)
在从Ruby的控件发送路径名的字符串之前使用类似的东西.
您必须确保您的程序知道它正在运行的操作系统,以便它可以决定何时需要它.一种方法是在程序运行开始时设置一个常量,类似这样
::USING_WINDOWS = !!((RUBY_PLATFORM =~ /(win|w)(32|64)$/) || (RUBY_PLATFORM=~ /mswin|mingw/))
(我知道这有效,但我没有写,所以我不明白双重爆炸...)
使用Pathname该类生成在您的系统上正确的路径:
a_path = Pathname.new("a_path_goes_here")
Run Code Online (Sandbox Code Playgroud)
这样做的好处是它允许您使用+运算符链接目录:
a_path + "another_path" + "and another"
Run Code Online (Sandbox Code Playgroud)
a_path.to_s然后,调用将为您所在的系统生成正确的路径.