Lesson contents

Ruby — Organizing code across files

In Ruby, require_relative loads a file relative to the calling file. A module can group the helper method under its own name.

A simple example

Load a library

  1. Start with 2, 2
  2. Do this Load Set and count unique values
  3. Result 1
Requiring set makes the Set class available. Both inputs refer to the same value.
lesson.rb
require "set"
puts Set.new([2, 2]).size
Output
1
Advertisements

Share a function between source files

require_relative resolves the helper relative to the calling file. The Boxes module groups a method under a name and avoids adding it to every object.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.

Run the example

Ruby 2.7 or later. Run these commands from the directory containing the example.

ruby lesson.rb
boxes.rb
module Boxes
  def self.remaining(capacity, used)
    capacity - used
  end
end
lesson.rb
require_relative "boxes"

puts Boxes.remaining(8, 3)
Output
5

Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.

Try it yourself

Change the used count from 3 to 8 in the caller.

Check your answer

Running the same command prints 0. No change to the helper is needed.

Ruby language documentation

Related tags

  • Ruby
  • modules
  • source files
  • imports