Last active
August 29, 2015 13:56
-
-
Save havenwood/9286846 to your computer and use it in GitHub Desktop.
Iterator beginning at `element` and iterating by `increment`.
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 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