Menu
CoddyTech

Modules as Namespaces

Lesson 26 of 48 in Coddy's Ruby for C Developers course.

C organizes declarations in headers and definitions in translation units, often using name prefixes and internal linkage for isolation. Ruby modules organize constants and methods at runtime, and require_relative loads neighboring files. Loading a file does not create a matching namespace. Ruby include adds behavior rather than acting like a C preprocessor include.

C: complete program

#include <stdio.h>
struct Pricing { int (*subtotal)(int, int); };
static int subtotal(int price, int quantity) {
    return price * quantity;
}
static const struct Pricing *pricing_api(void) {
    static const struct Pricing api = {subtotal};
    return &api;
}
int main(void) {
    const struct Pricing *pricing = pricing_api();
    printf("%d\n", pricing->subtotal(4, 3));
    return 0;
}

Ruby: complete program

module TextTools
  def self.shout(text)
    text.upcase
  end
end
puts TextTools.shout("elm")
challenge icon

Challenge

Easy

Define Shipping.fee(weight): 2 times weight plus 3, for integer weights 0..100. solve returns that fee.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, shipping.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'shipping'
def check(value)
  raise 'Public API check failed' unless value
end
check(Shipping.fee(11) == 25)

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for C Developers

Practice on your own: Online Ruby compiler