1

目前我正在获取路径,\\documents\videos\form.mov但需要将路径更改为/documents/videos/form.mov. 我尝试过使用路径分隔符和split. 但它不允许拆分路径,因为 '\' 是转义字符。

请任何人都可以帮助我。

4

2 回答 2

3
path = '\\\\documents\videos\form.mov'

new_path = path.gsub /\\+/, '/'

puts path, new_path

输出

\\documents\videos\form.mov
/documents/videos/form.mov

这是一个irb会话的副本

E:\Ruby\source>irb --simple-prompt
>> path = '\\\\documents\videos\form.mov'
=> "\\\\documents\\videos\\form.mov"
>> new_path = path.gsub /\\+/, '/'
=> "/documents/videos/form.mov"
>>
于 2013-08-06T14:10:02.190 回答
0

现有的答案不符合我的期望,所以我不得不自己动手。这是模块及其单元测试。

module ConvertWindowsPath
  def convert_windows_path windows_path
    manipulated_windows_path = windows_path.clone
    unix_path = ""
    if windows_path.start_with? "\\\\" #it's on some network thing
      unix_path = "//"
      manipulated_windows_path = manipulated_windows_path[2..-1]
    elsif manipulated_windows_path.start_with? "\\"
      unix_path = "/"
    end
    unix_path += manipulated_windows_path.split("\\").join("/")
    unix_path += "/" if manipulated_windows_path.end_with?("\\")
    unix_path
  end
end

require 'test/unit'

class ConvertWindowsPathTest < Test::Unit::TestCase
  include ConvertWindowsPath
  def setup
    @expectations = {
      "C:\\" => "C:/",
      "\\\\vmware-host\\Shared Folders\\Foo\\bar-baz" => "//vmware-host/Shared Folders/Foo/bar-baz",
      "D:\\Users\\ruby\\Desktop\\foo.txt" => "D:/Users/ruby/Desktop/foo.txt",
      "z:\\foo\\bar\\" => "z:/foo/bar/"
    }
  end
  def test_expectations
    @expectations.each do |windows_path, expected_unix_path|
      assert_equal expected_unix_path, convert_windows_path(windows_path)
    end
  end
end
于 2016-02-18T16:49:40.103 回答