Hi --

On Sat, 5 Feb 2005, Navindra Umanee wrote:

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

If your enumerable object has a size method, you can do:

   bottom_items.each_with_index do |item,i|
     do_something_with(...)
     unless i == bottom_items.size - 1
       ...
     end
   end

or something similar with #each_index.


David

-- 
David A. Black
dblack / wobblini.net