Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Name of Files and Directories in Ruby
3.
Listing Directories
4.
Testing Files
5.
Creating Files and Directories in Ruby
6.
Renaming Files and Directories in Ruby
7.
Deleting Files and Directories in Ruby
8.
Frequently Asked Questions
8.1.
What in Ruby is a directory?
8.2.
What in Ruby is a file?
8.3.
What occurs when a file is required in Ruby?
8.4.
How does Ruby generate directories?
8.5.
Which approach does Ruby use when writing to a file?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Files and Directories in Ruby

Introduction

A File is an abstraction of any file object the programme may access and is closely related to the class IO. A directory is a storage space for files. The Dir class and the FileUtils module manage directories in Ruby, whereas the File class handles files.

The File class offers a large number of class methods for interacting with files as filesystem entries, such as methods for validating the size or existence of a named file and methods for separating a filename from the directory name that precedes it. These class methods don't work with File objects; filenames are supplied as strings. The Dir class, likewise, offers class methods for working with and reading filenames from filesystem directories.

See the official documentation of ruby here and see the official faqs of ruby here.

Name of Files and Directories in Ruby

The File and Dir classes' class methods work with files and directories given a name. Ruby employs Unix-style filenames, with the character / serving as the directory separator. Ruby may be used on a Windows platform, and filenames can still contain the forward-slash character. Ruby can manage filenames on Windows that contain drive letter prefixes and the backslash character. All implementations should use the value '/' for the constant File::SEPARATOR. On Windows, File::ALT SEPARATOR is "," but on other operating systems, it is "nil."

Listing Directories

Using the Dir.entries method or the Dir, the foreach iterator is the most straightforward approach to enumerate the contents of a directory.

For example:

# Get the names of all files in the config/ directory
filenames = Dir.entries("config") # Get names as an array
Dir.foreach("config") {|filename| ... } # Iterate names
You can also try this code with Online Ruby Compiler
Run Code

 

The names provided by these methods, which on Unix-like platforms contain "." (the current directory) and ".." (the parent directory), are not guaranteed to be in any particular order—the Dir.[] operator may be used to get a list of files that match a specific pattern.

Testing Files

Several ways to get metadata on a named file or directory are defined by File. A large number of the techniques return low-level, OS-dependent data. Here, just the most lightweight and widely applicable options are shown. Use “ri” on the File and File::Stat classes for a comprehensive set of methods.

For example:

f = "/usr/bin/ruby" # A filename for the examples below

# File existence and types.

File.exist?(f) # Does the named file exist? Also: Does the file exist?
File.file?(f) # Is it an existing file?
File.directory?(f) # Or is it an existing directory?
File.symlink?(f) # Is it a symbolic link?

# File size methods. Use File.truncate to set file size.

File.size(f) # File size in bytes.
File.size?(f) # Size in bytes or nil if empty file.
File.zero?(f) # True if file is empty.

# File permissions. Use File.chmod to set permissions (system dependent).

File.readable?(f) # Can we read the file?
File.writable?(f) # Can we write the file? No "e" in "writable"
File.executable?(f) # Can we execute the file?
File.world_readable?(f) # Can everybody read it? Ruby 1.9.
File.world_writable?(f) # Can everybody write it? Ruby 1.9.

# File times/dates. Use File.utime to set the times.

File.mtime(f) # => Last modification time as a Time object
File.atime(f) # => Last access time as a Time object
You can also try this code with Online Ruby Compiler
Run Code

 

Using ftype, which produces a string naming the type, you may also determine the type of a filename (file, directory, symbolic link, etc.). Assuming that /usr/bin/ruby is a shortcut to /usr/bin/ruby1.9, here are some examples:

File.ftype("/usr/bin/ruby") # => "link"
File.ftype("/usr/bin/ruby1.9") # => "file"
File.ftype("/usr/lib/ruby") # => "directory"
File.ftype("/usr/bin/ruby3.0") # SystemCallError: No such file or directory
You can also try this code with Online Ruby Compiler
Run Code

Creating Files and Directories in Ruby

Below we have discusses how to create files and directories in ruby.

No unique methods exist for creating a file defined in the File class. Simply open it for writing, enter 0 or more bytes, and then shut it to create one. Open a file in append mode if you don't want to overwrite an already-existing one.

# Create (or overwrite) a file named "test"
File.open("test", "w") {}
# Create (but do not clobber) a file named "test"
File.open("test", "a") {}
You can also try this code with Online Ruby Compiler
Run Code

 

Use Dir.mkdir to create a new directory.

Dir.mkdir("temp") # Create a directory
You can also try this code with Online Ruby Compiler
Run Code

Renaming Files and Directories in Ruby

Below we have discussed how to rename files and directories in ruby.

Use File.rename to modify a file's name:

File.rename("test", "test.old") # Current name followed by new name
You can also try this code with Online Ruby Compiler
Run Code

 

To rename a directory, use.

require 'fileutils'
FileUtils.mv sourcedir, newdir
You can also try this code with Online Ruby Compiler
Run Code

Deleting Files and Directories in Ruby

Below we have discussed how to delete files and directories in ruby.

Use File.delete or unlink to remove a file or link.

File.delete("test2") # May also be called with multiple args
File.unlink("oldtest") # to delete multiple named files
You can also try this code with Online Ruby Compiler
Run Code

 

Use Dir.rmdir or one of its equivalents, Dir.delete or Dir.unlink, to remove a directory. Before being erased, the directory must be empty.

File.delete(*Dir["temp/*"]) # Delete all files in the directory
Dir.rmdir("temp") # Delete the directory
You can also try this code with Online Ruby Compiler
Run Code

Frequently Asked Questions

What in Ruby is a directory?

A place where files can be kept is in a directory. In Ruby, directories are managed by the FileUtils module and the Dir class, whereas the File class deals with files.

What in Ruby is a file?

A File is a class of IO objects that abstracts any file object accessible by the application. You may write (for example) File.exist?("foo") since File includes the module FileTest's class methods.

What occurs when a file is required in Ruby?

The need method in Ruby is used to load a different file and run all its instructions. This imports all of the file's class and method definitions.

How does Ruby generate directories?

The Dir. mkdir function in Ruby may be used to create new folders. This directory is created beneath the current path if a relative path is provided ( Dir. pwd ).

Which approach does Ruby use when writing to a file?

You can write material into a file using the syswrite technique. The file must be opened in write mode for this approach to work. In an existing file, the new material will replace the old content.

Conclusion

In this article, we have extensively discussed Files and Directories in ruby.

After reading about the files and directories in ruby, are you not feeling excited to read/explore more articles on the topic of DSA? Don't worry; Coding Ninjas has you covered. To learn, see Try Ruby, the History of Ruby and Constants in Ruby.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass