Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the current working directory's absolute path from irb

People also ask

How do I find the absolute path of a current directory?

The pwd command displays the full, absolute path of the current, or working, directory. It's not something you'll use all the time, but it can be incredibly handy when you get a bit discombobulated.

Which function is used to show the current working directory path?

The pwd command can be used to determine the present working directory. and the cd command can be used to change the current working directory.

How is current working directory determined?

The current working directory is the directory in which the user is currently working in. Each time you interact with your command prompt, you are working within a directory. By default, when you log into your Linux system, your current working directory is set to your home directory.

How do you find the absolute path in Ruby?

Pass a string to File. expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner's home directory.


Dir.pwd seems to do the trick.

http://ruby-doc.org/core/Dir.html#method-c-pwd


File.expand_path File.dirname(__FILE__) will return the directory relative to the file this command is called from.

But Dir.pwd returns the working directory (results identical to executing pwd in your terminal)


As for the path relative to the current executing script, since Ruby 2.0 you can also use

__dir__

So this is basically the same as

File.dirname(__FILE__)

This will give you the working directory of the current file.

File.dirname(__FILE__)

Example:

current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"

result: "/Users/nemrow/SITM/folder1/folder2"


Through this you can get absolute path of any file located in any directory.

File.join(Dir.pwd,'some-dir','some-file-name')

This will return

=> "/User/abc/xyz/some-dir/some-file-name"

If you want to get the full path of the directory of the current rb file:

File.expand_path('../', __FILE__)