検証付きの生成
Coddyの「C開発者のためのRuby」コースのレッスン 29/48。
Cのファクトリー関数は、初期化済みの構造体を返したり、ステータスを通じて無効な入力を報告したりできます。Rubyのクラスのシングルトンメソッドは、コンストラクションに意味のある名前を付けます。一方、initializeはインスタンスを設定します。クラスで呼び出されるファクトリーは、有効なコンストラクター引数を選択できます。適切な検証を行わなければ、どちらの言語もビジネス上の不変条件を自動的に強制することはありません。
C:完全なプログラム
#include <stdio.h>
struct Score{int points;};
static struct Score make_score(int points){struct Score result={points};return result;}
int main(void) {
struct Score score=make_score(7);printf("%d\n",score.points);
return 0;
}
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とbooleanをスペースで区切って返すか、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)
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C開発者のためのRubyのすべてのレッスン
自分で練習してみよう: Rubyオンラインコンパイラ