Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active August 29, 2015 13:59
Show Gist options
  • Save havenwood/10914614 to your computer and use it in GitHub Desktop.
Save havenwood/10914614 to your computer and use it in GitHub Desktop.
Array #next, #pred and #rewind.
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