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
- Start with 2, 2
- Do this Load Set and count unique values
- Result 1
require "set"
puts Set.new([2, 2]).size
1
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.
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
module Boxes
def self.remaining(capacity, used)
capacity - used
end
end
require_relative "boxes"
puts Boxes.remaining(8, 3)
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.