Menu
CoddyTech

Extending with Super

Lesson 33 of 48 in Coddy's Ruby for C Developers course.

C extends behavior by explicitly calling a helper, such as a base-record function, and combining its result. Ruby super continues lookup for the current method. Bare super forwards current arguments, while super() passes none. Distinguish augmenting the inherited result from replacing it, and preserve the required method signature.

C: complete program

#include <stdio.h>
struct Base { int price; };
struct Child { struct Base base; int fee; };
static int base_total(const struct Base *self, int quantity)
{
    return self->price * quantity;
}
static int child_total(const struct Child *self, int quantity)
{
    return base_total(&self->base, quantity) + self->fee;
}
int main(void)
{
    struct Child child = {{3}, 2};
    printf("%d\n", child_total(&child, 4));
    return 0;
}

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 icon

Challenge

Easy

Define 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for C Developers

Practice on your own: Online Ruby compiler