Iteration the ruby way

Lähettäjä: Kaspar Schiess <eule@space.ch>
Aihe: Re: iteration the ruby way
(In response to news:1107566961.943586.81760@g14g2000cwa.googlegroups.com

by William James)

Shouldn't that be

ary[0...-1].each {|e| do_something(e) }
do_something_else(ary.last)

or

ary[0..-2].each {|e| do_something(e) }
do_something_else(ary.last)

?

I would prefer this solution for its clarity of expression.

Me too :slight_smile: I just think the #inject won on the neat-o factor,
particularly since it seemed adequate for the OP.

kaspar

E

"E S" <eero.saynatkari@kolumbus.fi> schrieb im Newsbeitrag news:20050206143902.PIMQ15813.fep31-app.kolumbus.fi@mta.imail.kolumbus.fi...

Lähettäjä: Kaspar Schiess <eule@space.ch>
Aihe: Re: iteration the ruby way
(In response to news:1107566961.943586.81760@g14g2000cwa.googlegroups.com

by William James)

Shouldn't that be

ary[0...-1].each {|e| do_something(e) }
do_something_else(ary.last)

or

ary[0..-2].each {|e| do_something(e) }
do_something_else(ary.last)

?

I would prefer this solution for its clarity of expression.

Me too :slight_smile: I just think the #inject won on the neat-o factor,
particularly since it seemed adequate for the OP.

Partly yes and partly no: apart from the cute factor, there is a real advantage of the inject solutions show: they work for *all* Enumerables while the array indexing works only for arrays. So #inject is more general. Also, Array# creates a new array instance along the way which is a bit inefficient. But I do agree that the indexing might be more readable.

Kind regards

    robert