From: Robert Klemme Date: 2011-05-18T20:12:43+09:00 Subject: Re: Making fibers enumerable On Wed, May 18, 2011 at 9:39 AM, Rahul Kumar wrote: > Hi, > > Most of the `Enumerable` methods can be used for fiber based generators if > `Fiber` is made enumerable. > > class Fiber >  include Enumerable >  def each >    loop { yield self.resume } >  end > end > > def fib_gen >  Fiber.new { >    a, b = 0, 1 >    while true >      Fiber.yield a >      a, b = b, a + b >    end >  } > end > > # Find the fibonacci number greater than 1000 > fib_gen.find {|x| x > 1000 } > # take first 10 fibonacci numbers > fib_gen.take 10 > # take_while numbers are smaller than 1000 > fib_gen.take_while {|x| x < 1000 } > > If it could be the default behavior, it would be very useful. Some methods > won't be applicable, particularly for non-terminating generators in their > default incarnation viz. drop_while. It can either be re-written to advance > the generator using Fiber#resume or it can be left upto the user to handle > infinite sequences correctly. > > If I understand correctly, writing generators was one of the purposes of > fibers. Why can't fibers be made enumerable by default? I am not sure how that interacts with the original intent of Fibers: their main purpose is to bring coroutines to Ruby. http://en.wikipedia.org/wiki/Coroutines How would your example look if there was another generation that you wanted to do concurrently? Because for the single threaded generator case there is already a tool: Enumerator.new. The example in the documentation even uses Fibonacci Numbers as example. :-) http://www.ruby-doc.org/core/classes/Enumerator.html#M000299 fib_gen = Enumerator.new { |y| a = b = 1 loop { y << a a, b = b, a + b } } Now you can do exactly the same as you did with your example # Find the fibonacci number greater than 1000 fib_gen.find {|x| x > 1000 } # take first 10 fibonacci numbers fib_gen.take 10 # take_while numbers are smaller than 1000 fib_gen.take_while {|x| x < 1000 } For this Fiber would be the wrong tool. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/