Yielding to a Block
Lesson 17 of 48 in Coddy's Ruby for C Developers course.
C callbacks use explicitly typed function pointers; retained state normally travels through an additional context pointer with a managed lifetime. Ruby methods accept an implicit block and invoke it with yield. This is synchronous unless the surrounding API says otherwise. Yielding without a supplied block raises LocalJumpError unless the method provides a fallback.
C: complete program
#include <stdio.h>
#include <ctype.h>
static void shout(const char *word) {
for(;*word;++word)putchar(toupper((unsigned char)*word));puts("!");
}
static void announce(void (*action)(const char *)) {action("hello");}
int main(void) {
announce(shout);
return 0;
}
Ruby: complete program
def announce
yield "hello"
end
puts announce { |word| word.upcase + "!" }Challenge
EasyDefine 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for C Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: Borrow3Collections and Blocks
Arrays and IndexingHashes and Missing KeysYielding to a BlockMap and SelectReduce and PredicatesRecap: Repeated CodesPractice on your own: Online Ruby compiler