Ruby:Windows 路径转换 [英] Ruby: windows path conversion

查看:39
本文介绍了Ruby:Windows 路径转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在我的脚本中使用长路径,因为我在 Windows 上,所以我必须将这些长路径转换为带有斜杠而不是反斜杠的 nix 样式.如果此后您复制该路径以转到该文件夹​​,没有什么困难但很烦人,因为在资源管理器中您必须再次执行相反的操作.

I often use long paths in my scripts and since i'm on windows i have to convert these long paths to nix style with slashes in stead of backslashes. Nothing difficult but annoying if thereafter you copy that path to go to that folder since in explorer you have to do the opposite again.

所以我创建了一个进行转换的函数,现在我可以使用可以复制的 windowspaths 并让 Ruby 满意.

So i made a function that does the conversion, now i can use windowspaths that i can copy around and keep Ruby sattisfied.

问题:这里有更优雅的解决方案吗?我不喜欢第二个 gsub 在他开始时处理双 \ ,也想在最后处理 \ (目前不可能).该函数应该能够处理网络 unc (\..) 和本地驱动路径 (c:..)

Question: is there a more elegant solution here ? I don't like the second gsub to handle the double \ at he beginning and also would like to handle a \ at the end (currently not possible). The function should be able to handle network unc's (\..) and local drivepaths (c:..)

class String 
  def path
    self.gsub('\\','/').gsub(/^\//,'//')
  end
end

path = '\\server\share\folder'.path

Dir.glob(path+'**/*') do |file|
  puts file
end

#=>
#//server/share/folder/file1.txt
#//server/share/folder/file2.txt

推荐答案

使用 File.join 的建议让我尝试了常规的 split &加入,现在我有了这个版本,摆脱了丑陋的双 gsub,现在它更长了,但可以处理结尾斜线.有人有更好的版本吗?

The suggestion to use File.join made me try a regular split & join and now i have this version, got rid of the ugly double gsub, now it's longer but can handle an ending slash. Has someone a better version ?

class String
  def to_path(end_slash=false)
    "#{'/' if self[0]=='\\'}#{self.split('\\').join('/')}#{'/' if end_slash}" 
  end 
end

puts '\\server\share\folder'.to_path(true) #//server/share/folder/
puts 'c:\folder'.to_path      #c:/folder

这篇关于Ruby:Windows 路径转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆