Composing Objects
Lesson 31 of 48 in Coddy's Ruby for C Developers course.
C composition can embed a value or retain a pointer to a collaborator, with different copying and lifetime implications. Ruby instance variables retain object references; assignment does not clone the collaborator or transfer exclusive ownership. Delegation supports flexible behavior without inheritance. Inject a compatible object and invoke its methods through the intended contract.
C: complete program
#include <stdio.h>
struct Policy {
int factor;
int (*apply)(const struct Policy *self, int quantity);
};
struct Order { const struct Policy *policy; };
static int multiply(const struct Policy *self, int quantity)
{
return self->factor * quantity;
}
static int order_total(const struct Order *self, int quantity)
{
return self->policy->apply(self->policy, quantity);
}
int main(void)
{
struct Policy policy = {2, multiply};
struct Order order = {&policy};
printf("%d\n", order_total(&order, 3));
return 0;
}Ruby: complete program
class Lens
def label; "wide"; end
end
class Camera
def initialize(lens); @lens = lens; end
def label; @lens.label; end
end
puts Camera.new(Lens.new).labelChallenge
EasyDefine Leg(minutes) with minutes reader; Route with add(leg) and total. Route starts empty, stores supplied legs, and sums minutes. solve reads leg durations and returns total.
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, leg.rb, route.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'leg'
require_relative 'route'
def check(value)
raise 'Public API check failed' unless value
end
a = Route.new; b = Route.new
a.add(Leg.new(7)); a.add(Leg.new(2))
check(a.total == 9 && b.total == 0 && Leg.new(4).minutes == 4)
puts solve(STDIN.read)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for C Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: Borrow3Collections and Blocks
Arrays and IndexingHashes and Missing KeysYielding to a BlockMap and SelectReduce and PredicatesRecap: Repeated Codes6Composition and Dispatch
Composing ObjectsInheritance and OverridesExtending with SuperModules as MixinsDuck-Typed CollaboratorsRecap: ReceiptsPractice on your own: Online Ruby compiler