superで拡張する
Coddyの「Go開発者のためのRuby」コースのレッスン 33/48。
Goでは、埋め込みフィールドのメソッドを明示的に呼び出して、その結果を拡張できます。Rubyのsuperは、チェーン内のモジュールも含めてメソッドの検索を続けます。引数なしのsuperは現在の引数を引き渡し、super()は引数を渡しません。埋め込みを想像上のGoのスーパークラス操作として訳すのではなく、拡張と置き換えの違いを保ってください。
Go:完全なプログラム
package main
import ("fmt")
type Tool struct{}
func(Tool)Features()string{return "read"}
type Editor struct{Tool}
func(e Editor)Features()string{return e.Tool.Features()+",write"}
func main(){
fmt.Println(Editor{}.Features())
}
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)
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Go開発者のためのRubyのすべてのレッスン
自分で練習してみよう: Rubyオンラインコンパイラ