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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources