I have a string that represents a file path, such as "/home/user/dir1/dir2/dir3/name.ext". Now I'd like to convert it to a legal URI (a string starting with "file://" and so on).
How do I do it in Ruby?
require 'uri'
uri = URI.join('file:///', '/home/user/dir1/dir2/dir3/name.ext')
=> #<URI::Generic:0x0000000263fcc0 URL:file:/home/user/dir1/dir2/dir3/name.ext>
uri.scheme
=> "file"
uri.path
=> "/home/user/dir1/dir2/dir3/name.ext"
uri.to_s
=> "file:/home/user/dir1/dir2/dir3/name.ext"
Since Ruby 2.6.3 use can use URI::File
path = '/somewhere/on/your/drive'
URI::File.build([nil, path])
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