Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Dealing with Directories in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 303
    Comment on it

    Ruby is a rich technology and its integration with system commands makes it much more richer. In Ruby if you want to create, read, delete or change the directory, there is Dir class available for that, which provides multiple methods for dealing with directories. Some important ways of operating on directories using ruby are:

    a) Creating a Directory:
    To create a directory in ruby, the mkdir method of Dir class is used like this:

    Dir.mkdir("new_dir")
    
    #=> This will create a new_dir, you can manually specify the full path wherever you want to create the directory


    b) Deleting a Directory:
    To delete a directory, delete method of Dir class is used. It raises an error if the directory is not empty or doesn't exist

    Dir.delete("new_dir")
    
    #=> This will remove the new_dir directory if it exists and is empty


    c) Changing the Directory:
    If you want to navigate from directory to another in a program, you can use chdir method.

    Dir.chdir("lib/tasks")
    
    #=> This will change the current directory to lib/tasks

    d) Get the current location:
    pwd method is used to get the current location of the directory:

    Dir.pwd
    #=> "/home/user/rails_apps/ror_ecommerce_app"

    e) Getting the contents of the directory:
    To get the contents of the directory including files and directories, entries command is used that returns an array containing all the directories and files inside that directory

    Dir.entries("new_dir")
    #=> ["dir1", "dir2", "file1", "file2"]

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: