Recap - Custom Iterator
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 20 of 56.
Build your own iterator method that uses yield, accepts a block, and returns a useful value, combining everything from this chapter.
Challenge
MediumDefine a method named each_even that takes an array numbers and yields each even number in the array to its block (skipping odd numbers entirely).
Then read a comma-separated list of integers, call each_even on it with a block that prints "Even: <n>" for every yielded value, and finally print:
Done: <count>Where count is how many even numbers were yielded.
For input 1,2,3,4,5,6, the output is:
Even: 2
Even: 4
Even: 6
Done: 3Try it yourself
# TODO: define each_even(numbers) that yields every even number
numbers = gets.chomp.split(",").map(&:to_i)
count = 0
# TODO: call each_even with a block that prints "Even: <n>"
# and increments count for each yielded value
puts "Done: #{count}"
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier