Custom Enumerable
Lesson 40 of 48 in Coddy's Ruby for Go Developers course.
Go can expose an explicit cursor returning a value and success flag, as shown here, while range provides other traversal forms. Ruby each commonly returns an Enumerator when no block is supplied, and next raises StopIteration at exhaustion. Both approaches retain state between advances. Specify ordering, repeated traversal and mutation behavior explicitly.
Go: complete program
package main
import ("fmt")
type Cursor struct{next,end int}
func(c *Cursor)Next()(int,bool){if c.next>=c.end{return 0,false};value:=c.next;c.next++;return value,true}
func main(){
cursor:=Cursor{next:2,end:5};if value,ok:=cursor.Next();ok{fmt.Println(value)};if value,ok:=cursor.Next();ok{fmt.Println(value)}
}
Ruby: complete program
it = (2...5).each
puts it.next
puts it.nextChallenge
EasyDefine 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Go Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip4Mutation and Errors
Mutation and AliasesNil and Optional ValuesExceptions and ValidationEnsure and CleanupRecap: Safe Ratio7Objects in Practice
Ordering with ComparableCopies and Frozen ValuesLambdas and Captured StateCustom EnumerableRecap: Callable FilterRecap: Limited Store2Flow 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: BorrowPractice on your own: Online Ruby compiler