検証付きの構築
Coddyの「C#開発者のためのRuby」コースのレッスン 29/48。
C#のstaticファクトリーとRubyのクラスシングルトンメソッドは、名前付きの構築経路を提供します。Rubyのinitializeはインスタンスのセットアップフックとして機能し、ファクトリーはクラスオブジェクトに対して呼び出されます。ファクトリーは有効な引数を選択したり、セットアップの詳細を隠したりできます。ファクトリー名やアクセサーの宣言だけで、すべてのドメイン不変条件が自動的に確立されるわけではありません。
C#: 完全なプログラム
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(Mode.Manual().Automatic);
class Mode {public bool Automatic {get;} private Mode(bool automatic){Automatic=automatic;} public static Mode Manual()=>new Mode(false);}
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)からテキストを返します。ロックされたドライバーは、返されたテキストを最後に改行を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オンラインコンパイラ