From: Zakaria Date: 2001-09-01T22:12:56+09:00 Subject: [ruby-talk:20666] Re: Relative path Assalamu'alaikum wr. wb. "Gardian, Milan" wrote: > Hello, > what is the shortest & quickest way of finding a relative path between path1 > and path2 in Ruby? (either universal or Win32 platform-specific)... > Thank you for your help! Here's the UNIX version, feel free to make the Windows version. --------------------------------------------------- #!/usr/bin/ruby -w def strip_common_dir(path1, path2) if path1+"\t"+path2 =~ %r{^(.*/)(.*?)\t\1(.*)$} path1, path2 = $2, $3 end return path1, path2 end def rel_path(path1, path2) path1, path2 = strip_common_dir path1, path2 return ('../' * path1.count('/')) + path2 end def rel_path_dir(dir1, dir2) dir1 += '/' if dir1[-1,1] != '/' dir2 += '/' if dir2[-1,1] != '/' return rel_path dir1, dir2 end def test_path(path1, path2) puts "Rel path of '#{path1}' and '#{path2}' is '#{rel_path_dir path1, path2}'" end path1 = '/temp/foo' path2 = '/temp/foo/dir/another_dir/' path3 = '/special_dir' test_path path1, path2 test_path path1, path3 test_path path2, path1 test_path path2, path3 test_path path3, path1 test_path path3, path2 --------------------------------------------------- > Cheers, > Milan Wassallam, -- Zakaria Work: zakaria@asia-karsa.com, http://asia-karsa.com Private: z4k4ri4@bigfoot.com Yahoo!: z4k4ri4 http://pemula.linux.or.id