Extending with Super
Lesson 33 of 48 in Coddy's Ruby for Java Developers course.
Java super explicitly names a parent operation or constructor. Ruby super continues lookup for the same method name and may encounter included modules. Ruby bare super forwards current arguments; parentheses with no arguments deliberately send none. Reuse parent behavior when extending it, rather than copying its implementation.
Java: complete program
import java.util.*;
public class Main {
static class Tool { List<String> features() { return List.of("read"); } }
static class Editor extends Tool {
@Override List<String> features() {
List<String> result = new ArrayList<>(super.features());
result.add("write"); return result;
}
}
public static void main(String[] args) {
System.out.println(String.join(",", new Editor().features()));
}
}Ruby: complete program
class Tool
def features; ["read"]; end
end
class Editor < Tool
def features; super + ["write"]; end
end
puts Editor.new.features.join(",")Challenge
EasyDefine BaseLabel initialized with text, with render returning that text. FramedLabel inherits BaseLabel, accepts text and mark, uses parent initialization and returns mark+parent_render+mark. solve input has text and a single-character mark.
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, base_label.rb, framed_label.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'base_label'
require_relative 'framed_label'
def check(value)
raise 'Public API check failed' unless value
end
check(BaseLabel.new("raw").render == "raw")
check(FramedLabel.new("branch", "!").render == "!branch!")
check(FramedLabel.new("x", "?").is_a?(BaseLabel))
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 Java 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