WoNáDo
3/11/2005 9:57:00 AM
--
Wolfgang Nádasi-Donner
wonado@donnerweb.de
"Wolfgang Nádasi-Donner" <wonado@donnerweb.de> schrieb im Newsbeitrag
news:39d6okF61jtpsU1@uni-berlin.de...
> --
> Wolfgang Nádasi-Donner
> wonado@donnerweb.de
> "Roshan James" <roshanj@microsoft.com> schrieb im Newsbeitrag
>
news:E8AA887D9A078F45B870125A37ED234701BC9564@APS-MSG-02.southpacific.corp.m
> icrosoft.com...
> > I have been wondering is there is a way to do this. Can I have two
> > itertors working in lock-step - ie, can I have both of them return a
> > value each into the same loop body ?
> >
> > a = [1, 2, 3, 4]
> > b = [5, 6, 7, 8]
> > a.each {|a1|
> > b.each {|b1|
> > # this nests the call to b inside a
> > }
> > }
> >
> > Is there someway I can do something like -
> > a = [1, 2, 3, 4]
> > b = [5, 6, 7, 8]
> > (a.each, b.each) {|a1, b1|
> > #so that I get one value from a and one from b
> > }
> >
> > I hope I have made the idea clear, the above syntax is only illustrative
> > of what I mean.
> >
> > This is possible in python because the iterators are fundamentally
> > objects that require an explicit next() call and are not bound to the
> > the loop body/block by syntax as in ruby.
> >
> > Thanks in advance,
> > Roshan
> >
> >
> >
>
> the following works. It is oriented on the length of the first array. If
the
> second one is longer the rest of the values are ignored, if it is shorter,
> "nil" will be returned.
>
> >>>> code >>>>>
> class Array
> def combeach(anarr)
> self.each_index{|ind|
> yield self[ind], anarr[ind]
> }
> end
> end
>
> a=[1,2,3,4,5,6]
> b=[7,8,9]
>
> a.combeach(b){|ai,bi| print "ai=#{ai.inspect}, bi=#{bi.inspect}\n"}
> >>>>> Result >>>>>
> ai=1, bi=7
> ai=2, bi=8
> ai=3, bi=9
> ai=4, bi=nil
> ai=5, bi=nil
> ai=6, bi=nil
> >>>>> End Of Example >>>>>
>
> Good luck.
>
>
As I've seen in the last message you are directly looking for the "external
iterators", as implemented in C#.
Why? - It is somehow the "assembler-way" for iterators. The difference is
that you must put your algorthmic selection inside a method an then call the
block using "yield". This doesn't even make problems if you read a data
stream which length is not specified when starting the action.