From: Jason Persampieri Date: 2002-11-27T13:32:24+09:00 Subject: Re: each_with_index & collect_with_index? > It would be really cool if, instead of having a > million *_with_index > methods floating around in Enumerable, we had a > method which could be > used inside a block to retrieve the number of > iterations that the block > has undergone. > > For instance: > > class Array > def collect( &e ) > ary = [] > i = 0 > self.each { |item| > eval( "def index; #{i} end", e ) > ary.push( e.call( item ) ) > i += 1 > } > return ary > end > end > > The `index' method can then be used in the block: > > c = z.collect { |el| f(el, a[index], b[index]) } > > This implementation is flawed, though, because it > creates the `index' > method in whatever namespace the block is originally > placed. But, you > know.. what if?? > > _why > > (Bear in mind... I'm a newbie ;) Wow... I like this... or at least an slight variation. Why not have a global var (eg $# or something) that keeps the current index whenever you're iterating through an array/string/whatever? It would be consistent, extremely useful, less confusing and completely straightforward. OK... let the criticism flow! Jason