Modules as Mixins
Lesson 34 of 48 in Coddy's Ruby for PHP Developers course.
PHP traits and Ruby modules both share behavior across classes, but their composition and lookup rules differ. PHP has explicit trait conflict-resolution syntax. Ruby include adds the module to the ancestor chain, and later lookup can use super. A Ruby module can also be a namespace; it is not an instantiable class.
PHP: complete program
<?php
trait Tagged { public function tag() { return "tracked"; } }
class Parcel { use Tagged; }
echo (new Parcel())->tag(), "\n";Ruby: complete program
module Tagged
def tag; "tracked"; end
end
class Parcel
include Tagged
end
puts Parcel.new.tagChallenge
EasyDefine CostPair module with pair_cost(n) returning cost(n)+cost(n). Flat includes it, has initialize(amount) and cost(n) returning amount. PerUnit includes it, initialized with rate and cost(n) returning rate*n. Input is flat or unit, amount and units; return pair_cost.
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, cost_pair.rb, flat.rb, per_unit.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'cost_pair'
require_relative 'flat'
require_relative 'per_unit'
def check(value)
raise 'Public API check failed' unless value
end
check(Flat.ancestors.include?(CostPair) && PerUnit.ancestors.include?(CostPair))
check(Flat.new(7).cost(2) == 7 && PerUnit.new(3).cost(2) == 6)
probe = Class.new { include CostPair; def cost(n); n + 4; end }.new
check(probe.pair_cost(3) == 14)
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 PHP 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