Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to check if a file exists in Ruby

okwudili onyejiaku

Overview

We can check if a file exists in Ruby by using the exists?() method of the File class. This method returns a Boolean value signifying if the file exists or not.

Syntax

File.exists?(file_name)

Parameters

file_name: This is the name of the file whose existence we want to check.

Return value

This method returns a Boolean value. It returns true if the file exists, and false if it doesn’t.

Code example

main.rb
test.txt
# Create file names
fn1 = "main.rb"
fn2 = "test.txt"
fn3 = "fake.txt"
fn4 = "empty.txt"

# Check if the files exist
puts File.exists?(fn1)
puts File.exists?(fn2)
puts File.exists?(fn3)
puts File.exists?(fn4)
Checking if some files exist in Ruby

Explanation

  • Lines 2 to 5: We create some file names, of both files that exist and those that do not.
  • Lines 8 to 11: We check if the files exist. Then, we print the results to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring