Menu
CoddyTech

Yielding to a Block

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

GDScript normally passes a Callable explicitly and invokes call, while Ruby methods receive an implicit block and can invoke yield. Both can separate traversal from caller-supplied behavior. Yield without a block raises LocalJumpError unless the method checks block_given? or provides a fallback. A Ruby block can retain lexical bindings, but its capture behavior differs from GDScript value capture.

GDScript: complete program

extends SceneTree
func announce(action: Callable):
    return action.call("hello")

func _init():
    print(announce(func(word): return word.to_upper() + "!"))
    quit()

Ruby: complete program

def announce
  yield "hello"
end
puts announce { |word| word.upcase + "!" }
challenge icon

Challenge

Easy

Define transform_pair(a,b) which calls its supplied block once for a and once for b, in that order, and returns the two results in an array. solve reads two integers, triples each using the block and joins results with spaces.

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, transform.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'transform'
def check(value)
  raise 'Public API check failed' unless value
end
seen = []
check(transform_pair("oak", "elm") { |s| seen << s; s.upcase } == ["OAK", "ELM"])
check(seen == ["oak", "elm"])

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