How do I get the name of the current directory in Ruby?

30,982

Solution 1

dirname = File.basename(Dir.getwd)

File.basename() returns the base name even when its argument is the path of a directory.

To get absolute path, Dir.pwd seems to do the trick.

Solution 2

In Ruby 2.0 or greater, you can use Kernel#__dir__:

__dir__

From the docs:

Returns the canonicalized absolute path of the directory of the file from which this method is called.

Solution 3

File.expand_path(File.dirname(File.dirname(__FILE__)))
Share:
30,982
Orcris
Author by

Orcris

Updated on January 28, 2020

Comments

  • Orcris
    Orcris over 4 years

    How do I get the name of the current directory in Ruby? All I've found is File.dirname(__FILE__), but that only returns . and I want the actual name. How do I do this?