Last active
September 25, 2017 16:38
-
-
Save mklbtz/1dc8351ebebb17e2539b3864efb0a7ac to your computer and use it in GitHub Desktop.
A quick way to make enumerable objects from an arbitrary block
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
class AnyEnumerable | |
include Enumerable | |
def initialize(&each_impl) | |
@each_impl = each_impl | |
end | |
def each(&block) | |
@each_impl.call(&block) | |
end | |
end | |
sequence = AnyEnumerable.new do |&block| | |
last = 12 | |
i = 0 | |
while i <= last | |
block.call i | |
i += 1 | |
end | |
end | |
sequence.map do |i| | |
i.to_s | |
end # => ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"] | |
sequence.take(5) # => [0, 1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment