From: MenTaLguY Date: 2005-12-12T21:56:54+09:00 Subject: Re: increasing counter whithin loop? --=-us/gmAu5eyUEfFNwK1Ai Content-Type: text/plain Content-Transfer-Encoding: quoted-printable On Mon, 2005-12-12 at 21:07 +0900, Patrick Gundlach wrote: > Your two solutions are very nice, thank you. I think I'll go for the > each_with_next. Cool. Note that (per the recent thread with Matz) I was wrong about needing to program the iterator defensively for redo/next. Those confine their effects to the block, and you'd handle retry/break with 'ensure' like you would other exits (e.g. exceptions), but normally you don't need to care. Anyway, this is sufficient for each_with_next: module Enumerable def each_with_next(last=3Dnil) prev =3D nil first =3D true each do |elt| if first first =3D false next else yield prev, elt end prev =3D elt end yield prev, last unless first end end > There are other items in the schedule that I need to output. I collect > all these parts in an array: >=20 > @schedule << ListOfMember.new.parse(the source) > .... >=20 > and output all like >=20 > @schedule.each { |elt| elt.render } >=20 > but in case of two 'ListOfMembers' following each other, they should be > output next to each other, so I wrap them in a 'Group of two ListOfMember= s' Hmm. What happens if you have three in a row? Seems to me you could do something like this: collapsed =3D [] @schedule.each do |elt| prev =3D collapsed.last if LOM =3D=3D=3D prev && LOM =3D=3D=3D elt grp =3D GOLM.new grp.add( prev ) grp.add( elt ) collapsed[-1] =3D grp elsif GOLM =3D=3D=3D prev && LOM =3D=3D=3D elt prev.add( elt ) else collapsed << elt end end collapsed.each { |elt| elt.render } Lookbehind + a little mutation. No magic iterators required... -mental --=-us/gmAu5eyUEfFNwK1Ai Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) iD8DBQBDnXPFcUNIGiXCc4MRAloKAJ9mD253zu1PdqpH4WHKVmHURW5NGgCfUHei /LWoUjC3y+ZfgrSDOdwNQw8= =SmwA -----END PGP SIGNATURE----- --=-us/gmAu5eyUEfFNwK1Ai--