Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/9286846 to your computer and use it in GitHub Desktop.
Save havenwood/9286846 to your computer and use it in GitHub Desktop.
Iterator beginning at `element` and iterating by `increment`.
module Iterator
def self.new element, increment = 1
Enumerator.new do |iteration|
loop do
iteration << element
increment.abs.times do
element = if increment >= 0
element.next if element.respond_to? :next
else
if element.respond_to? :pred
element.pred
elsif element.respond_to? :ord
element.ord.pred.chr
end
end
end
end
end
end
end
Iterator.new('a').first(3)
#=> ["a", "b", "c"]
Iterator.new('A', 5).first(3)
#=> ["A", "F", "K"]
Iterator.new(10, 10).first(3)
#=> [10, 20, 30]
Iterator.new(1, -1).first(3)
#=> [1, 0, -1]
Iterator.new('c', -1).first(3)
#=> ["c", "b", "a"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment