slash and backslash in Ruby

后端 未结 5 715
北荒
北荒 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 02:11

    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...)

提交回复
热议问题