How to get the path of a file without normalisation in ruby?

75 Views Asked by At

My current directory path is /a/b/c/ When I do

fname = File.path("../test.rb")
::File.absolute_path(fname) 

output is: /a/b/test.rb

What I am expecting is the output something like this: /a/b/c/../test.rb

Basically I need the path of a file without normalisation of ../ and ~

3

There are 3 best solutions below

2
Damian On

Can you try File.realpath() methods. For example:

fname = File.realpath("test.rb", __dir__)

This will give you the absolute path with '..' references intact.

0
Stefan On

You could build it yourself via File.join:

Dir.pwd
#=> "/a/b/c"

File.join(Dir.pwd, "../test.rb")
#=> "/a/b/c/../test.rb"

Note that Dir.pwd returns the current working directory. To get the current file's directory, use __dir__.

2
Pascal On

UPDATE: not what OP wants, see comment by Stefan.

You want to expand_path

3.0.6 :003 > Dir.pwd
 => "/something/somewhere"
3.0.6 :004 > File.expand_path("../foo")
 => "/something/foo"
3.0.6 :005 >