构造时验证
Coddy 面向 Rust 开发者的 Ruby 课程的第 29 课,共 48 课。
Rust 关联函数可以返回构造好的值,也可以返回 Result 来表示拒绝。Ruby 类单例方法可以提供工厂方法,而 initialize 用于设置实例。两者都应在返回前建立不变条件。Rust 中惯用的名称 new 并不是自动构造钩子,也不等同于 Ruby 的 new/initialize 协议。
Rust:完整程序
struct Score{points:i32}
impl Score{fn new(points:i32)->Self{Self{points}}}
fn main(){
println!("{}",Score::new(7).points);
}
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;返回 width 和布尔值,两者之间用空格分隔,否则返回 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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器