How to split the code across multiple files in Ruby

Introduction

File handling is pretty common in multiple programming languages, as it allows us to access different components and code files. It can manage assets, load images, and even import databases onto your project.

One other common use of this in Ruby is to split code for simplification and better understanding. As the code gets longer, locating the code functions and debugging them is challenging. We can simplify this process by spreading the code across multiple files. This will help in increasing the readability of the code, and whenever we run into a problem, we can exactly locate and debug the problem faster.

A demonstration of using different files in the main file

The example below will help you understand the concept better. Suppose we are writing a game with more than 1000 lines of code. To simplify this problem, we can create a separate file for each function and copy the code into that file. We can then call this function in the main file by first importing the file using the keyword require_relative. Once the file is imported, we can call the function anywhere in the file without any issues.

Example

main.rb
happy_birthday.rb
#require_relative to import file into main file.
require_relative "happy_birthday"
#calling imported function.
happy_birthday("Alex",22)

Explanation

main.rb

  • Line 2: The require_relative keyword is used to import another file. The path to the file that we are looking for is provided.
  • Line 4: The imported function happy_birthday is called. Two parameters are passed in the function: the name and the age of the person receiving the birthday wish.

happy_birthday.rb

  • Lines 1–3: A function happy_birthday() is defined, which takes in two arguments, name and age, and displays a birthday wish.

Note: The function name and file name can be different, but they are kept the same for easy understanding and to make it easy to locate a file for a specific function.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved