Menu
CoddyTech

기본값과 키워드

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

표준 C에는 기본 매개변수나 키워드 매개변수가 없습니다. 래퍼와 옵션 구조체를 사용하면 비슷한 계약을 표현할 수 있습니다. Ruby는 위치 인수의 기본값과 키워드 인수를 직접 제공합니다. Ruby 3에서는 위치 인수 해시와 키워드 인수를 구분하므로, 키워드 인수를 전달할 때는 명시적으로 더블 스플랫 확장을 사용하세요. 옵션 값에서 누락과 0의 차이를 유지하세요.

C: 완전한 프로그램

#include <stdbool.h>
#include <stdio.h>
struct Options { bool has_repetitions; int repetitions; };
static int repetitions(struct Options options) {
    return options.has_repetitions ? options.repetitions : 2;
}
int main(void) {
    struct Options missing = {false, 0};
    struct Options zero = {true, 0};
    printf("%d:%d\n", repetitions(missing), repetitions(zero));
    return 0;
}

Ruby: 완전한 프로그램

def border(text, mark: ".")
  mark + text + mark
end
puts border("x")
puts border("x", mark: "!")
challenge icon

챌린지

쉬움

units*rate-discount를 반환하는 charge(units, rate: 4, discount: 0)를 정의하세요. 입력에는 units만 있거나, units rate 또는 units rate discount가 있습니다. 생략된 필드에는 solve가 기본값을 사용해야 합니다.

출력하지 말고 solve(input)에서 텍스트를 반환하세요. 잠긴 드라이버는 반환된 텍스트를 마지막에 줄바꿈 하나를 붙여 출력하고, 필수 공개 API를 별도로 확인합니다.

코드는 exercise.rb, pricing.rb에 작성하세요. main.rb에는 제공된 입출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

require_relative 'exercise'
require_relative 'pricing'
def check(value)
  raise 'Public API check failed' unless value
end
check(charge(7) == 28)
check(charge(7, discount: 3) == 25)
check(charge(2, rate: 9, discount: 1) == 17)

puts solve(STDIN.read)
quiz icon실력 점검

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

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

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