From: E S Date: 2005-02-05T07:37:23+09:00 Subject: Re: iteration the ruby way > L�hett�j�: Navindra Umanee > Aihe: Re: iteration the ruby way > > John Wilger 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) ary.each_index {|i| do_smth(ary[i]) unless i == ary.size - 1} > Thanks, > Navin. E