Modules as Namespaces
Lesson 26 of 48 in Coddy's Ruby for PHP Developers course.
PHP namespaces qualify declarations, and static methods can group operations on a class. Ruby modules can group constants and singleton methods, but file loading does not automatically create a namespace. Use require_relative explicitly for neighboring Ruby files. Ruby module inclusion is a different operation from importing a PHP name with use.
PHP: complete program
<?php
class TextTools {
public static function shout($text) { return strtoupper($text); }
}
echo TextTools::shout("elm"), "\n";Ruby: complete program
module TextTools
def self.shout(text)
text.upcase
end
end
puts TextTools.shout("elm")Challenge
EasyDefine 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)
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: BorrowPractice on your own: Online Ruby compiler