Last active
August 29, 2015 13:59
-
-
Save havenwood/10914614 to your computer and use it in GitHub Desktop.
Array #next, #pred and #rewind.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ArrayIteration | |
def next | |
@index ||= 0 | |
raise StopIteration, 'iteration reached an end' if @index.next > size | |
@index += 1 | |
self[@index.pred] | |
end | |
def pred | |
@index ||= 0 | |
raise StopIteration, 'iteration reached an end' if @index.pred < 1 | |
@index -= 1 | |
self[@index.pred] | |
end | |
def rewind | |
@index = 0 | |
self | |
end | |
end | |
class Array | |
include ArrayIteration | |
end | |
a = [:x, :y, :z] | |
a.next #=> :x | |
a.next #=> :y | |
a.next #=> :z | |
a.next # StopIteration: iteration reached an end | |
a.rewind #=> [:x, :y, :z] | |
a.next #=> :x | |
a.next #=> :y | |
a.pred #=> :x | |
a.pred # StopIteration: iteration reached an end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment