Validated Construction
Lesson 29 of 48 in Coddy's Ruby for PHP Developers course.
PHP static factory methods can provide meaningful named construction paths. Ruby class singleton methods serve a similar role and commonly call new. Ruby initialize is invoked during construction rather than being the public factory operation. The fixed manual-mode factory demonstrates naming without implementing the task's interval validation.
PHP: complete program
<?php
class Mode {
public $automatic;
public function __construct($automatic) { $this->automatic = $automatic; }
public static function manual() { return new self(false); }
}
echo Mode::manual()->automatic ? "true\n" : "false\n";Ruby: complete program
class Mode
attr_reader :automatic
def initialize(automatic)
@automatic = automatic
end
def self.manual
new(false)
end
end
puts Mode.manual.automaticChallenge
EasyDefine Interval.new(low,high), raising ArgumentError when low>high. Provide width (high-low) and include?(value), inclusive at both ends. solve reads low high query; return width and boolean separated by a space, or invalid.
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, interval.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'interval'
def check(value)
raise 'Public API check failed' unless value
end
r = Interval.new(-4, 2)
check(r.width == 6 && r.include?(-4) && !r.include?(3))
begin
Interval.new(2, 1)
raise "Expected rejection"
rescue ArgumentError
end
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