Menu
CoddyTech

superによる拡張

Coddyの「C開発者のためのRuby」コースのレッスン 33/48。

Cでは、基底レコード関数などのヘルパーを明示的に呼び出し、その結果を組み合わせて動作を拡張します。Rubyのsuperは、現在のメソッドの検索を続けます。引数なしのsuperは現在の引数を転送し、super()は引数を渡しません。継承した結果を拡張する場合と置き換える場合を区別し、必要なメソッドシグネチャを維持しましょう。

C:完全なプログラム

#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:完全なプログラム

class Tool
  def features; ["read"]; end
end
class Editor < Tool
  def features; super + ["write"]; end
end
puts Editor.new.features.join(",")
challenge icon

チャレンジ

簡単

textで初期化され、renderがそのtextを返すBaseLabelを定義します。FramedLabelはBaseLabelを継承し、textとmarkを受け取り、親クラスの初期化を使用して、mark+親クラスのrender+markを返します。solveの入力にはtextと1文字のmarkが含まれます。

出力せずに、solve(input)からtextを返してください。ロックされたドライバーは、返されたtextを最後に改行を1つ付けて出力し、必要な公開APIを個別にチェックします。

コードはexercise.rb、base_label.rb、framed_label.rbに記述してください。main.rbには提供された入力/出力コードが含まれており、編集できません。

自分で試してみよう

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 icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C開発者のためのRubyのすべてのレッスン

自分で練習してみよう: Rubyオンラインコンパイラ