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?
Ruby has a method for this case. It is File::expand_path . 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 canonical path is always an absolute and unique path. If String pathname is used to create a file object, it simply returns the pathname. This method first converts this pathname to absolute form if needed. To do that it will invoke the getAbsolutePath() Method and then maps it to its unique form.
In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.
Pathname represents the name of a file or directory on the filesystem, but not the file itself. The pathname depends on the Operating System: Unix, Windows, etc.
require 'pathname' Pathname.new("a/b/../c/x").cleanpath
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"
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