superを使った拡張
Coddyの「C#開発者のためのRuby」コースのレッスン 33/48。
C#のbaseは、オーバーライドで結果を拡張するときに、基底クラスの実装を明示的に呼び出します。Rubyのsuperは、現在のメソッドの検索を続け、モジュールをたどる場合もあります。引数なしのsuperは引数を引き継ぎ、super()は引数を渡しません。呼び出し名を機械的に翻訳するのではなく、継承した動作を拡張するのか置き換えるのかを維持してください。
C#: 完全なプログラム
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(new Editor().Features());
class Tool {public virtual string Features()=>"read";}
class Editor:Tool {public override string Features()=>base.Features()+",write";}
Ruby: 完全なプログラム
class Tool
def features; ["read"]; end
end
class Editor < Tool
def features; super + ["write"]; end
end
puts Editor.new.features.join(",")チャレンジ
簡単テキストで初期化され、renderがそのテキストを返すBaseLabelを定義します。FramedLabelはBaseLabelを継承し、テキストとマークを受け取り、親クラスの初期化を使い、マーク+親のrender+マークを返します。solveの入力には、テキストと1文字のマークが含まれます。
出力せずに、solve(input)からテキストを返してください。ロックされたドライバーは、返されたテキストを最後に改行を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)
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C#開発者のためのRubyのすべてのレッスン
自分で練習してみよう: Rubyオンラインコンパイラ