Menu
Coddy logo textTech

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 icon

Challenge

Medium

Define 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: 3

Try 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