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 namesfn1 = "main.rb"fn2 = "test1.txt"fn3 = "."fn4 = "./"fn5 = "./test1.txt"# Check if the file names are directoriesputs File.directory?(fn1) # falseputs File.directory?(fn2) # falseputs File.directory?(fn3) # trueputs File.directory?(fn4) # trueputs File.directory?(fn5) # false
Explanation
- Lines 2 to 6: We create some file name variables. We create a file
test1.txtand an application code filemain.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.