Topic 13
Topic 13
Ruby source files are converted directly from the English source tree.
Overview
Why this topic matters ๐ก
Recursion and closures are both powerful ideas, but students often meet them as isolated syntax tricks. This topic teaches them through a sequence of small problems: recurse over nested structures first, then build closures that capture query behavior, then combine both ideas in one traversal service.
Learning outcomes ๐ฏ
By the end of this topic, students should be able to:
Assessment focus โ
Students should be able to explain why the recursive traversal and the matching rule are separated instead of embedded into one large method.
Short Note
Recursion is useful when the data shape repeats itself:
Closures are useful when behavior should remember a value from the place where it was created:
Ruby beauty in this topic:
Ruby caution in this topic:
Reflection prompt:
Worked Examples
Example 1: Nested number structures ๐ก
Summing nested numbers is a useful first recursion exercise because the repeated shape is obvious. Each child is either:
That makes it easier for students to see what recursion is doing.
Example 2: Search predicates as closures ๐ก
A closure is realistic when a user provides a search term and the code needs a small reusable matcher:
matcher = TitleMatchers . containing ( "ruby" ) matcher . call ( "Ruby Blocks" ) # => true worked_examples.md ruby This is better than hard-coding the search term inside the traversal.