slash and backslash in Ruby

后端 未结 5 738
北荒
北荒 2021-01-04 01:16

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

5条回答
  •  感情败类
    2021-01-04 01:52

    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.open(File.join(Dir.pwd, "Desktop", "file.txt"), "r")
    => #
    
    File.join(Dir.pwd, "Desktop", "file.txt")
    => "C/Documents and Settings/Users/prince/Desktop/file.txt"
    

提交回复
热议问题