検証付きの生成
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)からテキストを返します。ロックされたドライバーは、返されたテキストの末尾に改行を1つ付けて出力し、必要な公開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オンラインコンパイラ