views:

38

answers:

2

Is there an easy way in Ruby to find a canonical file path out of a messy file path?

For example:

  • a/b/../c/x is the same as a/c/x
  • a/./b/c/x is the same as a/b/c/x
  • a/./b/../../c/x is the same as c/x

Any simple way to do this?

+4  A: 
Pathname.new("a/b/../c/x").cleanpath
Ken Bloom
+2  A: 

File.expand_path(file_name [, dir_string] ) → abs_file_name

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a ~, which expands to the process owner‘s home directory (the environment variable HOME must be set correctly). ~user expands to the named user‘s home directory.

File.expand_path("~oracle/bin")           #=> "/home/oracle/bin"
File.expand_path("../../bin", "/tmp/x")   #=> "/bin"
Matt Briggs