Menu
CoddyTech

検証付きの構築

Coddyの「Go開発者のためのRuby」コースのレッスン 29/48。

Goのコンストラクター関数は、値またはポインターを返し、エラーを返すこともあります。Rubyのクラスシングルトンメソッドは名前付きファクトリーとして機能し、initializeはインスタンスのセットアップを処理できます。ファクトリーはクラスオブジェクトに対して呼び出されます。命名規則に頼って構築を検証するのではなく、結果を公開する前に不変条件を確立しましょう。

Go:完全なプログラム

package main
import ("fmt")
type Score struct{Points int}
func NewScore(points int)Score{return Score{Points:points}}

func main(){
fmt.Println(NewScore(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
challenge icon

チャレンジ

簡単

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)
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Go開発者のためのRubyのすべてのレッスン

自分で練習してみよう: Rubyオンラインコンパイラ