ruby - How can Enumerator stop in the middle of method execution? -
(example ruby tapas episode. 59)
@names = %w[ylva brighid shifra yesamin] def names yield @names.shift yield @names.shift yield @names.shift yield @names.shift end enum = to_enum(:names) enum.next # => ylva @names # => ["brighid", "shifra", "yesamin"]
names
method execution seems stop after first line. if names
executed entirely, @names
should become empty. how can magic (= calling method partially) happen?
it working expected. on invocation enum.next calls first line in names method , yields caller, i.e. stops flow of execution of names method @ point. on next invocation enum.next flow of execution picked point left off.
ruby has object called fiber might demonstrate more succinctly: http://apidock.com/ruby/fiber allow 'pause execution' @ arbitrary point in program calling fiber.yield
, resume
left off @ later time.
for example, example above:
@names = %w[ylva brighid shifra yesamin] fiber = fiber.new fiber.yield @names.shift # yields control caller fiber.yield @names.shift fiber.yield @names.shift fiber.yield @names.shift end # resume calls give control fiber @ point left off puts fiber.resume #=> ylva puts fiber.resume #=> brighid puts fiber.resume #=> shifra puts fiber.resume #=> yesamin