Iteration the ruby way

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

···

> John Wilger <johnwilger@gmail.com> wrote:

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)

?

(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