Dario Daic
dariodaic5.1@gmail.com


>> dariodaic
/
Enumerators
-
Are they worth it?
Worth as a criteria
functionalities gained by X
------------------------------------------------------
time invested in learning X
X - Enumerator class
Enumerable module
few_iterators = [:map, :select, :sort, :inject, :count]
for iterator in few_iterators do
puts "There is a 'for' loop in Ruby!? ^^"
end
- it's a module
- it defines a bunch of iterators
- it requires host class to define an #each method
Enumerator class
enumerator = Enumerator.new do |yielder|
yielder.yield 1
yielder.yield 2
yielder.yield 3
end
enumerator.map { |n| n * 100 }
- it's a class
- it has objects
- it includes Enumerable
- it requires external collection
iterate (ˈɪtəˌreɪt)
- to do something over again or repeatedly
enumerate (ɪˈnjuːməˌreɪt)
- to determine the number of; count
VS
iterator
METHOD
VS
enumerator
INSTANCE
3 ways to create an enumerator:
Enumerator#new()- Enumerator#new /w block
- #to_enum & #enum_for
- via blockless iterator
What does an enumerator require to function?
- must hook up to an external collection
- uses a default method - #each
#learnbydoing


What does it provide in return?
- enables both internal and external iteration
- lets us economize on object creation when chaining methods
- endows collections it hooks up on with enumerability
- protects objects from modification
What gotchas you should watch out for?
- it can un-override methods of a class
- it can be confusing to read if not understood correctly
- "enumerator literacy" - David A. Black
External iteration
Way of manipulating execution of internal iteration.
- #next - get next value that is going to be yielded
- #feed - return specified value from a yield
- #rewind - return internal iterator to the beginning
- StopIteration#result - fetch a return value of internal iteration
Lazy enumerator
- Ordinary enumerator is eager
- Lazy enumerator is, well...lazy
- created using #lazy or #lazy_enum
- enumeration has to be forced
- uses Generator and Yielder differently
Conclusion(s)
Is it simple and intuitive? No, it's complex and weird.
Is it neccessary? No, it might come in hand sometimes.
So, is it worth it?
Its worth is inversely proportional to that of Enumerable.
Mmm...barely. :)
References
Benjamin Tan Wei Hao:
http://www.sitepoint.com/implementing-lazy-enumerables-in-ruby/
Pat Shaughnessy:
http://patshaughnessy.net/2013/4/3/ruby-2-0-works-hard-so-you-can-be-lazy
David A. Black:
https://www.manning.com/books/the-well-grounded-rubyist-second-edition
Enumerators
By Dario Daic
Enumerators
Brief look into Ruby Enumerator class and what it has to offer.
- 561