Menu
CoddyTech

Custom Enumerable

Lesson 40 of 48 in Coddy's Ruby for R Developers course.

Base R can model incremental traversal with a closure retaining a cursor, as shown here, but has no single Ruby Enumerable protocol for every collection. Ruby each normally yields values with a block and returns an Enumerator without one. Enumerator#next raises StopIteration on exhaustion, unlike this source’s NULL sentinel. Specify ordering, repeated traversal and mutation behavior explicitly.

R: complete program

iterator <- function(first,last){current <- first;function(){if(current>=last)return(NULL);value <- current;current <<- current+1;value}}
next_value <- iterator(2,5)
cat(next_value(),"\n",sep="")
cat(next_value(),"\n",sep="")

Ruby: complete program

it = (2...5).each
puts it.next
puts it.next
challenge icon

Challenge

Easy

Define Window(values), copying the supplied integer array, including Enumerable and implementing each. With a block, yield values in order and return self; without a block return an Enumerator. solve returns sum of odd values using the object's Enumerable methods.

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

Try it yourself

require_relative 'exercise'
require_relative 'window'
def check(value)
  raise 'Public API check failed' unless value
end
v = [8, 2]; w = Window.new(v); v << 9
seen = []; check(w.each { |n| seen << n }.equal?(w))
check(seen == [8, 2] && w.each.to_a == [8, 2] && w.map { |n| n + 1 } == [9, 3])

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 R Developers

Practice on your own: Online Ruby compiler