经过验证的构造
Coddy 面向 GDScript 开发者的 Ruby 课程的第 29 课,共 48 课。
GDScript 的静态工厂方法和 Ruby 的类单例方法可以为构造过程提供描述性名称。Ruby 的 initialize 仍然是实例设置钩子,而工厂方法则在类对象上调用。应先验证再公开构造出的值,而不是指望类名来确立不变量。对于返回状态的源工厂,在 Ruby 中可能需要明确的异常或结果契约。
GDScript:完整程序
extends SceneTree
class Score:
var points
func _init(value):
points = value
static func make(value):
return Score.new(value)
func _init():
print(Score.make(7).points)
quit()
Ruby:完整程序
class Mode
attr_reader :automatic
def initialize(automatic)
@automatic = automatic
end
def self.manual
new(false)
end
end
puts Mode.manual.automatic挑战
简单定义 Interval.new(low,high),当 low>high 时引发 ArgumentError。提供 width(high-low)和 include?(value),两端都包含在内。solve 读取 low、high 和 query;返回以空格分隔的宽度和布尔值,或者 invalid。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会在返回的文本末尾添加一个换行符并打印,同时独立检查所需的公共 API。
你的代码写在 exercise.rb、interval.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'interval'
def check(value)
raise 'Public API check failed' unless value
end
r = Interval.new(-4, 2)
check(r.width == 6 && r.include?(-4) && !r.include?(3))
begin
Interval.new(2, 1)
raise "Expected rejection"
rescue ArgumentError
end
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器