Menu
CoddyTech

Composing Objects

Lesson 31 of 48 in Coddy's Ruby for GDScript Developers course.

GDScript and Ruby can retain collaborators by reference and delegate calls to them. Assignment does not clone a child or transfer exclusive ownership. GDScript static annotations can constrain a collaborator, while dynamic calls and Ruby duck typing rely on compatible methods. Document required arguments, results and mutation behavior so delegation remains safe when another implementation is injected.

GDScript: complete program

extends SceneTree
class Policy:
    var factor
    func _init(value):
        factor = value
    func apply(n):
        return n * factor
class Model:
    var policy
    func _init(chosen_policy):
        policy = chosen_policy
    func total(n):
        return policy.apply(n)
func _init():
    var model = Model.new(Policy.new(4))
    print(model.total(3))
    quit()

Ruby: complete program

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

Challenge

Easy

Define Leg(minutes) with minutes reader; Route with add(leg) and total. Route starts empty, stores supplied legs, and sums minutes. solve reads leg durations and returns total.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, leg.rb, route.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for GDScript Developers

Practice on your own: Online Ruby compiler