[ruby-talk:02388] Re: Iterator into array

From: Clemens Hintze <c.hintze@...>
Date: 2000-04-07 23:23:52 UTC
List: ruby-talk #2388
Dave Thomas writes:
> kjana@os.xaxon.ne.jp (YANAGAWA Kazuhisa) writes:

...

> Say I have a method which generates Fibonacci numbers to to a limit:
> 
>   def fibUpTo(max)
>     i1, i2 = 1, 1
>     while i1 <= max
>       yield i1
>       i1, i2 = i2, i1+i2
>     end
>   end
> 
> I can do something like
> 
>  result = []
>  fibUpTo(20) { |f| result << f }
> 
> to collect the results into an array. However, to use Enumerable,
> wouldn't I have to wrap it all in a class?

...

> This just seems like a lot of work (he said, lazily). It would be nice 
> to be able to use the iterator method directly to achieve the same
> thing.

But I could not imagine how it should work! Look onto your 'fibUpTo'
method. It returns nothing. From where should the values you want to
have come from?

The only I could think of would be:

   def collectIteratorArgs(mid, *args)
     res = Array.new
     mid = method(mid.id2name) if mid.is_a? Symbol
     mid.call(*args) { | *n | res += n }
     res
   end
   
   def fibUpTo(max)
     i1, i2 = 1, 1
     while i1 <= max
       yield i1
       i1, i2 = i2, i1+i2
     end
   end
   
   p collectIteratorArgs(:fibUpTo, 20)
   p collectIteratorArgs({1=>"hello",2=>"world"}.method("each_pair"))

or:

   def collector(res)
     proc { | *n | res.push *n }
   end
   
   fibUpTo(20, &collector(result=[])); p result
   {1=>"hello",2=>"world"}.each_pair &collector(result=[]); p result

But cannot find another way right now. Sorry!

> Dave

\cle

-- 
Clemens Hintze  mailto: c.hintze@gmx.net

In This Thread