Skip to content

Instantly share code, notes, and snippets.

@mklbtz
Last active September 25, 2017 16:38
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 mklbtz/1dc8351ebebb17e2539b3864efb0a7ac to your computer and use it in GitHub Desktop.
Save mklbtz/1dc8351ebebb17e2539b3864efb0a7ac to your computer and use it in GitHub Desktop.
A quick way to make enumerable objects from an arbitrary block
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