Ruby Directories

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Ruby Directories

Class Dir has directory streams as objects which represents directories in underlying file system.

Directories are handled with Dir class.


Creating a Directory

To create a directory mkdir command is used. You can give permission to a directory if you want.

Syntax:

Dir.mkdir "dirName" , permission 

Example:

  1. Dir.mkdir "project"  

We have created a directory "project" in out system.


Checking a Directory exists or not

To check whether a directory exists or not exists? Method is used.

Syntax:

  1. puts Dir.exists? "dirName"  

Example:

  1. #!/usr/bin/ruby   
  2.   
  3. puts Dir.exists? "project"   
  4. puts Dir.exists? "pproject"  

Output:

Ruby directories 1

the correct directory name display true and wrong directory name display false.

Current Working Directory

To know the current working directory pwd method is used.

Syntax:

  1. puts Dir.pwd  

Example:

puts Dir.pwd 

Output:

Ruby directories 2

Removing Directory

To remove a directory, rmdir, unlink or delete methods are used. They perform same function for a Ruby directory.

Syntax:

Dir.rmdir "dirName"

Example:

  1. #!/usr/bin/ruby   
  2.   
  3. Dir.rmdir "project"   
  4. puts Dir.exists? "project" 

Output:

Ruby directories 3

The exists method returns false as this directory is no longer present.