Prateek Sen
Prateek Sen

Reputation: 422

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

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 ~

Upvotes: 0

Views: 86

Answers (3)

Pascal
Pascal

Reputation: 8646

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 >

Upvotes: -1

Stefan
Stefan

Reputation: 114237

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__.

Upvotes: 2

Damian
Damian

Reputation: 56

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

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

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

Upvotes: 0

Related Questions