Menu
CoddyTech

믹스인으로서의 모듈

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

Luau는 테이블 간에 함수를 공유하거나 메타테이블을 통해 위임할 수 있지만, Ruby와 같은 모듈 포함(module-inclusion) 선언은 없습니다. Ruby의 include는 하나의 클래스 상위 클래스를 유지하면서 조상 체인(ancestor chain)에 인스턴스 메서드를 추가합니다. Extend는 특정 객체에 메서드를 추가합니다. 파일을 로드하는 것, 함수를 복사하는 것, 모듈을 포함하는 것은 서로 다른 작업입니다.

Luau: 전체 프로그램

local function hello()return "hello" end;local host={hello=hello};print(host.hello())

Ruby: 전체 프로그램

module Tagged
  def tag; "tracked"; end
end
class Parcel
  include Tagged
end
puts Parcel.new.tag
challenge icon

챌린지

쉬움

cost(n)+cost(n)을 반환하는 pair_cost(n)이 있는 CostPair 모듈을 정의하세요. Flat은 이 모듈을 include하며, initialize(amount)를 가지고 amount를 반환하는 cost(n)을 가집니다. PerUnit은 이 모듈을 include하며, rate로 초기화되고 rate*n을 반환하는 cost(n)을 가집니다. 입력은 flat 또는 unit, amount와 units입니다. pair_cost를 반환하세요.

출력하지 말고 solve(input)에서 텍스트를 반환하세요. 잠긴 드라이버 코드는 반환된 텍스트를 마지막 줄바꿈 하나와 함께 출력하며, 필요한 공개 API를 독립적으로 검사합니다.

작성한 코드는 exercise.rb, cost_pair.rb, flat.rb, per_unit.rb에 들어갑니다. main.rb에는 제공된 입력/출력 코드가 포함되어 있으며 수정할 수 없습니다.

직접 해보기

require_relative 'exercise'
require_relative 'cost_pair'
require_relative 'flat'
require_relative 'per_unit'
def check(value)
  raise 'Public API check failed' unless value
end
check(Flat.ancestors.include?(CostPair) && PerUnit.ancestors.include?(CostPair))
check(Flat.new(7).cost(2) == 7 && PerUnit.new(3).cost(2) == 6)
probe = Class.new { include CostPair; def cost(n); n + 4; end }.new
check(probe.pair_cost(3) == 14)

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

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

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

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