From: Rick DeNatale Date: 2007-07-21T03:24:55+09:00 Subject: Re: Array : each_with_index On 7/19/07, Marcel Molina Jr. wrote: > On Thu, Jul 19, 2007 at 03:46:10PM +0900, Vin Raja wrote: > > I have following lines > > > > m=['a','b','c'] > > puts m.each_with_index{|v,i| i} > > > > which output in: > > > > >ruby try.rb > > a > > b > > c > > >Exit code: 0 > > irb(main):003:0> m.each_with_index{|v,i| i} > => ["a", "b", "c"] > irb(main):004:0> m.each_with_index{|v,i| p i} > 0 > 1 > 2 > => ["a", "b", "c"] > > The i variable in the block is indeed the index. But the result of the entire > each_with_index expression is not the result of each block invocation, but the collection > of all the array elements. > > marcel > -- > Marcel Molina Jr. Actually Enumerable#each_with_index appears to return the receiver object itself, identity is preserved. irb(main):001:0> a = %w{a word array} => ["a", "word", "array"] irb(main):002:0> a.equal?(a.each_with_index {|e, i| [e, i]}) => true irb(main):003:0> a = (1..3) => 1..3 irb(main):004:0> a.equal?(a.each_with_index {|e, i| [e, i]}) => true Although this is not documented, and could of course be overridden in a class which includes enumerable or one of its subclasses. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/