Menu
CoddyTech

검증을 통한 생성

Coddy의 C 개발자를 위한 Ruby 코스 레슨. 48개 중 29번째.

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
challenge icon

챌린지

쉬움

Interval.new(low,high)를 정의하고, low>high일 때 ArgumentError를 발생시키세요. 양 끝을 모두 포함하는 width (high-low)와 include?(value)를 제공하세요. solve는 low high query를 읽고, 너비와 불리언을 공백으로 구분해 반환하거나 invalid를 반환합니다.

출력하지 말고 solve(input)에서 텍스트를 반환하세요. 잠긴 드라이버는 반환된 텍스트를 마지막에 개행 문자 하나를 붙여 출력하고, 필요한 공개 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실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 Ruby의 모든 레슨

직접 연습해 보세요: 온라인 Ruby 컴파일러