How to Get the Name of the Current Working Directory in Ruby

Contents
In this article, you will learn how to get the name of the current working directory in Ruby.
Getting the name of the current working directory
In Ruby, you can get the name of the current working directory using the Dir class. The Dir.pwd method returns a string representing the current working directory.
Here is an example code snippet:
current_dir = Dir.pwd
puts "The current directory is: #{current_dir}"
This will output something like:
The current directory is: /path/to/current/directory
If you want to change the current directory, you can use the Dir.chdir method. For example:
Dir.chdir('/path/to/new/directory')
This will change the current directory to the specified path.
It’s worth noting that the Dir class provides many other useful methods for working with directories in Ruby. For example, you can use the Dir.entries method to get a list of all the files and directories in a given directory:
entries = Dir.entries('/path/to/directory')
puts entries.inspect
This will output something like:
[".", "..", "file1.txt", "file2.txt", "subdirectory"]
The Dir.glob method allows you to search for files or directories that match a specific pattern. For example:
matching_files = Dir.glob('/path/to/directory/*.txt')
puts matching_files.inspect
This will output a list of all the .txt files in the directory.