Convert URI path

I have a line representing the path to a file such as "/home/user/dir1/dir2/dir3/name.ext". Now I would like to convert it to a legal URI (a line starting with "file: //", etc.).

How to do it in Ruby?

+4
source share
2 answers
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"
+6
source
path = '/somewhere/on/your/drive'
URI::File.build([nil, path])
0
source

All Articles