Skip to content

Commit

Permalink
Add READMEs for Iterator.
Browse files Browse the repository at this point in the history
  • Loading branch information
aimee daniells committed Mar 30, 2010
1 parent 6d3766f commit 459b003
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.textile
Expand Up @@ -15,5 +15,6 @@ These are the patterns that i have implemented so far:
* "Strategy":http://github.com/sermoa/ruby_design_patterns/tree/master/behavioral_patterns/strategy/
* "Decorator":http://github.com/sermoa/ruby_design_patterns/tree/master/structural_patterns/decorator/
* "Composite":http://github.com/sermoa/ruby_design_patterns/tree/master/structural_patterns/composite/
* "Iterator":http://github.com/sermoa/ruby_design_patterns/tree/master/behavioral_patterns/iterator/

Please feel welcome to comment, add your feedback, suggest alternative implementations, point out my errors, and of course use for your own study and benefit. For a fast reference on how to implement design patterns in Ruby, i also recommend "shvets/design_patterns_in_ruby":http://github.com/shvets/design_patterns_in_ruby/.
Please feel welcome to comment, add your feedback, suggest alternative implementations, point out my errors, and of course use for your own study and benefit. For a fast reference on how to implement design patterns in Ruby, i also recommend "shvets/design_patterns_in_ruby":http://github.com/shvets/design_patterns_in_ruby/.
9 changes: 9 additions & 0 deletions behavioral_patterns/iterator/README.textile
@@ -0,0 +1,9 @@
h2. Iterator

bq. Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

So we all know that Ruby provides a very neat internal iterator using @Enumerable@ and the @each@ method which takes a block. We have no control over where and when the internal iterator moves its own index on; it just figures it out by itself.

To make an external iterator i defined @first@, @next@ and @done?@ methods for a ListIterator class. The client (which in this case happens to be the test) is responsible for moving the index via those exposed methods. The client does not need to know where the index is currently: we can quite easily define a ReverseIterator which goes through the list backwards. As far as the client is concerned, that doesn't matter, but the iterator provides a useful way of accessing the items in the list.

Even though an array can easily be traversed using Ruby's built in internal iterator, i decided to make my own version of an internal iterator anyway, to make sure i understood it. I called the method @each_item@ and i figured out that the internal iterator needed to accept a block, yield the item at its current index in order to perform the block, and move its index on.

0 comments on commit 459b003

Please sign in to comment.