検証付きの生成
Coddyの「Kotlin開発者のためのRuby」コースのレッスン 29/48。
Kotlinのコンパニオンオブジェクト関数は、クラス名を通じて呼び出せるファクトリを提供できます。Rubyのクラスシングルトンメソッドは名前付きファクトリを提供し、initializeがインスタンスの設定を処理します。呼び出し構文は似ていますが、これらは異なるオブジェクトモデルです。ファクトリ名が不変条件を保証すると頼るのではなく、オブジェクトを返す前に不変条件を検証しましょう。
Kotlin:完全なプログラム
class Score(val points:Int){companion object{fun make(n:Int)=Score(n)}}
fun main(){
println(Score.make(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)
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Kotlin開発者のためのRubyのすべてのレッスン
自分で練習してみよう: Rubyオンラインコンパイラ