What is the File.directory?() method in Ruby?

Overview

We use the File.directory?() method in Ruby to check if a particular file name is a directory. A directory is a folder that holds files in your computer system.

The File.directory?() method returns a Boolean value. If the file name provided is not a directory, it returns a false value. Otherwise, it returns a true value.

Syntax

File.directory?(file_name)

Parameters

file_name: This is the name of the file or symlink that points to a directory.

Return value

This method returns a Boolean value. If the file name provided is a directory, it returns true. If not, it returns false.

Code example

main.rb
test1.txt
# Get the file names
fn1 = "main.rb"
fn2 = "test1.txt"
fn3 = "."
fn4 = "./"
fn5 = "./test1.txt"
# Check if the file names are directories
puts File.directory?(fn1) # false
puts File.directory?(fn2) # false
puts File.directory?(fn3) # true
puts File.directory?(fn4) # true
puts File.directory?(fn5) # false

Explanation

  • Lines 2 to 6: We create some file name variables. We create a file test1.txt and an application code file main.rb.
  • Lines 9 to 13: We check if the file names we created are directories using the directory?() method of the file class. Then, we print the results.

Free Resources