[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: iteration the ruby way

e

2/4/2005 10:57:00 PM

> Lähettäjä: E S <eero.saynatkari@kolumbus.fi>
> Aihe: Re: iteration the ruby way
>
> > Lähettäjä: Navindra Umanee <navindra@cs.mcgill.ca>
> > Aihe: Re: iteration the ruby way
> >
> > John Wilger <johnwilger@gmail.com> wrote:
> > > > I have a question about The Ruby Way. Pickaxe gives the following
> > > > example for using iterators in Ruby:
> > > >
> > > > a = [ "a", "b", "c" ]
> > > > a.each {|x| print x, " -- " }
> > > >
> > > > This outputs:
> > > >
> > > > a -- b -- c --
> > > >
> > > > But what if I want to print "a -- b -- c"? What's the proper Ruby way
> > > > of doing that?
> > >
> > > a = ["a","b","c"]
> > > puts a.join(' - ')
> >
> > I guess I over-simplified. I really want to do computations based on
> > each element and compute my output. However, it's slightly different
> > for the last element. I would like to detect the last element in the
> > iteration.
> >
> > For example:
> >
> > bottom_items.each{ |item|
> > do_something_with(item[0], item[1], item[2])
> > if_not_last_item_do_this
> > }
>
> Since you're not doing the same thing on all elements, these should
> be conceptually correct.
>
> ary = ary[0..-1].each {|el| do_something el }
> do_something_else!(ary.last)

Bah, mail client snipped that... should have been

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

# Or

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

Depending on the context.

> ary.each_index {|i| do_smth(ary[i]) unless i == ary.size - 1}
>
> > Thanks,
> > Navin.

E



2 Answers

William James

2/5/2005 1:29:00 AM

0


E S wrote:

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

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)

?

Kaspar Schiess

2/6/2005 12:29:00 PM

0

(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.

kaspar

code manufacture - ruby lab
www.tua.ch/ruby