模块作为混入
Coddy 面向 GDScript 开发者的 Ruby 课程的第 34 课,共 48 课。
GDScript 通常通过组合或类继承来复用行为,而不是像 Ruby 那样使用模块 include。Ruby 的 include 会将模块插入实例方法查找过程,同时保留一个类父类。extend 则会为单个对象添加方法。混入可能依赖宿主方法,因此要记录这一约定。模块也可以用作命名空间,而且不像类那样被实例化。
GDScript:完整程序
extends SceneTree
class Greeting:
func hello():
return "hello"
class Host:
var greeting = Greeting.new()
func hello():
return greeting.hello()
func _init():
print(Host.new().hello())
quit()
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) 和返回 amount 的 cost(n)。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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器