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.
So i made a function that does the conversion, now i can use windowspaths that i can copy around and keep Ruby sattisfied.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With