Menu
CoddyTech

객체 조합하기

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

C에서는 값 자체를 포함하거나 협력 객체의 포인터를 보관할 수 있으며, 복사와 수명에 미치는 영향은 서로 다릅니다. Ruby의 인스턴스 변수는 객체 참조를 보관합니다. 대입은 협력 객체를 복제하거나 독점적 소유권을 이전하지 않습니다. 위임을 사용하면 상속 없이도 유연한 동작을 구현할 수 있습니다. 호환되는 객체를 주입하고 의도된 계약에 따라 해당 객체의 메서드를 호출하세요.

C: 완성된 프로그램

#include <stdio.h>
struct Policy {
    int factor;
    int (*apply)(const struct Policy *self, int quantity);
};
struct Order { const struct Policy *policy; };
static int multiply(const struct Policy *self, int quantity)
{
    return self->factor * quantity;
}
static int order_total(const struct Order *self, int quantity)
{
    return self->policy->apply(self->policy, quantity);
}
int main(void)
{
    struct Policy policy = {2, multiply};
    struct Order order = {&policy};
    printf("%d\n", order_total(&order, 3));
    return 0;
}

Ruby: 완성된 프로그램

class Lens
  def label; "wide"; end
end
class Camera
  def initialize(lens); @lens = lens; end
  def label; @lens.label; end
end
puts Camera.new(Lens.new).label
challenge icon

챌린지

쉬움

minutes 리더가 있는 Leg(minutes)를 정의하고, add(leg)와 total이 있는 Route를 정의하세요. Route는 비어 있는 상태로 시작해 전달된 legs를 저장하고 minutes를 합산합니다. solve는 leg의 소요 시간을 읽어 합계를 반환합니다.

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

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

직접 해보기

require_relative 'exercise'
require_relative 'leg'
require_relative 'route'
def check(value)
  raise 'Public API check failed' unless value
end
a = Route.new; b = Route.new
a.add(Leg.new(7)); a.add(Leg.new(2))
check(a.total == 9 && b.total == 0 && Leg.new(4).minutes == 4)

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

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

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

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