slash and backslash in Ruby

混江龙づ霸主 提交于 2019-12-18 18:52:05

问题


I want to write a application that works in windows and linux. but I have a path problem because windows use "\" and Linux use "/" .how can I solve this problem. thanks


回答1:


In Ruby, there is no difference between the paths in Linux or Windows. The path should be using / regardless of environment. So, for using any path in Windows, replace all \ with /. File#join will work for both Windows and Linux. For example, in 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"



回答2:


Take a look at File.join: http://www.ruby-doc.org/core/classes/File.html#M000031




回答3:


As long as Ruby is doing the work, / in path names is ok on Windows

Once you have to send a path for some other program to use, especially in a command line or something like a file upload in a browser, you have to convert the slashes to backslashes when running in Windows.

C:/projects/a_project/some_file.rb'.gsub('/', '\\') works a charm. (That is supposed to be a double backslash - this editor sees it as an escape even in single quotes.)

Use something like this just before sending the string for the path name out of Ruby's control.

You will have to make sure your program knows what OS it is running in so it can decide when this is needed. One way is to set a constant at the beginning of the program run, something like this

::USING_WINDOWS = !!((RUBY_PLATFORM =~ /(win|w)(32|64)$/) || (RUBY_PLATFORM=~ /mswin|mingw/))

(I know this works but I didn't write it so I don't understand the double bang...)




回答4:


Use the Pathname class to generate paths which then will be correct on your system:

a_path = Pathname.new("a_path_goes_here")

The benefit of this is that it will allow you to chain directories by using the + operator:

a_path + "another_path" + "and another"

Calling a_path.to_s will then generate the correct path for the system that you are on.




回答5:


Yes, it's annoying as a windows users to keep replacing those backslashes to slashes and vice-versa if you need the path to copy it to your filemanager, so i do it like his. It does no harm if you are on Linux or Mac and saves a lot of nuisance in windows.

path = 'I:\ebooks\dutch\_verdelen\Komma'.gsub(/\\/,'/')

Dir.glob("#{path}/**/*.epub").each do |file|
    puts file
end


来源:https://stackoverflow.com/questions/7173000/slash-and-backslash-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!