ミックスインとしてのモジュール
Coddyの「Go開発者のためのRuby」コースのレッスン 34/48。
Goの埋め込みと委譲は、Rubyのモジュールをインクルードする仕組みを使わずにメソッドを再利用します。Rubyのincludeは、クラスのスーパークラスを1つのままにして、インスタンスメソッドの検索対象にモジュールを追加します。extendは、特定のオブジェクトにメソッドを追加します。ミックスインはホストから提供されるメソッドに依存することがあるため、その契約をドキュメントに記載しましょう。モジュールのファイルを読み込むことは、別の手順です。
Go:完全なプログラム
package main
import ("fmt")
type Greeting struct{}
func(Greeting)Hello()string{return "hello"}
type Host struct{Greeting}
func main(){
h:=Host{};fmt.Println(h.Hello())
}
Ruby:完全なプログラム
module Tagged
def tag; "tracked"; end
end
class Parcel
include Tagged
end
puts Parcel.new.tagチャレンジ
簡単pair_cost(n) が cost(n)+cost(n) を返す CostPair モジュールを定義します。Flat はこれをインクルードし、initialize(amount) と amount を返す cost(n) を持ちます。PerUnit はこれをインクルードし、rate で初期化され、rate*n を返す cost(n) を持ちます。入力は flat または unit、amount、units です。pair_cost を返します。
出力せずに、solve(input) からテキストを返してください。ロックされたドライバーは、返されたテキストを最後に改行を1つ付けて出力し、必要な公開 API を個別に確認します。
コードは exercise.rb、cost_pair.rb、flat.rb、per_unit.rb に記述してください。main.rb には提供された入出力コードがあり、編集できません。
自分で試してみよう
require_relative 'exercise'
require_relative 'cost_pair'
require_relative 'flat'
require_relative 'per_unit'
def check(value)
raise 'Public API check failed' unless value
end
check(Flat.ancestors.include?(CostPair) && PerUnit.ancestors.include?(CostPair))
check(Flat.new(7).cost(2) == 7 && PerUnit.new(3).cost(2) == 6)
probe = Class.new { include CostPair; def cost(n); n + 4; end }.new
check(probe.pair_cost(3) == 14)
puts solve(STDIN.read)
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Go開発者のためのRubyのすべてのレッスン
自分で練習してみよう: Rubyオンラインコンパイラ