将模块用作混入
Coddy 面向 C# 开发者的 Ruby 课程的第 34 课,共 48 课。
C# 扩展方法提供静态解析的辅助语法,不会改变类的继承链。Ruby 的 include 会将模块加入实例方法查找链,并可能影响动态解析。两者都能复用行为,但分派规则不同。模块不是第二个类父类,include 也不同于加载其文件。
C#:完整程序
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(new Parcel().Tag());
class Parcel {}
static class Tags {public static string Tag(this Parcel parcel)=>"tracked";}
Ruby:完整程序
module Tagged
def tag; "tracked"; end
end
class Parcel
include Tagged
end
puts Parcel.new.tag挑战
简单定义 CostPair 模块,其中的 pair_cost(n) 返回 cost(n)+cost(n)。Flat 包含该模块,具有 initialize(amount),并且 cost(n) 返回 amount。PerUnit 包含该模块,使用 rate 初始化,并且 cost(n) 返回 rate*n。输入为 flat 或 unit、amount 和 units;返回 pair_cost。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,还会独立检查必需的公共 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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器