How to Load Files in Ruby

09/24/2021

Contents

In this article, you will learn how to load Files in Ruby.

Loading files in Ruby

In Ruby, loading files can be accomplished using several different methods. Here are some of the most common ways to load files in Ruby:

Using the require method

The require method is used to load a file that contains code that you want to use in your current file. For example, if you have a file called example.rb that contains a method called greet, you can load that file in another file by using the following code:

require './example.rb'

Note that the file path is relative to the current file. If the file you want to load is in a different directory, you can use an absolute path instead.

Using the load method

The load method is similar to the require method, but it loads the file every time it is called, instead of just once. For example, if you have a file called config.rb that contains configuration data, you can load it in your main file using the following code:

load './config.rb'

Using the require_relative method

The require_relative method is used to load a file that is relative to the current file. For example, if you have a file called helper_methods.rb in the same directory as your main file, you can load it using the following code:

require_relative 'helper_methods.rb'

Using the File class

You can also load files using the File class. For example, if you have a file called data.txt that contains data you want to read in your Ruby program, you can load it using the following code:

file = File.open('data.txt', 'r')

This will open the file in read-only mode. You can then read the contents of the file using the read method:

contents = file.read

Finally, remember to close the file when you’re done using it:

file.close