From: Harry Kakueki Date: 2009-06-12T21:04:43+09:00 Subject: Re: Idiomatic way to detect first/last iteration? On Fri, Jun 12, 2009 at 1:43 AM, Kendall Gifford wrote: > Hi there, is there any recognized ruby idiomatic way for detecting > when you're on the first and/or last iteration over a collection? Or, > if not, anyone know of any tricky ways? > > Specifically, I'm trying to avoid using each_with_index (as shown > below): > > genres = %w{ classical punk rock jazz } > genres.each_with_index do |genre, i| > desc = "one of my favorites" > desc = "my absolute favorite" if i.zero? > desc = "my least fav. of all my favorites" if i + 1 == genres.length > puts "#{genre} is #{desc}" > end > > I just don't like having to compare an index value (especially as when > detecting the final iteration) and hate even having it as a loop > parameter unless absolutely necessary. I know, I'm picky. Just wanted > to beat the bushes and see if any cool alternatives pop up. > > This is similar to some other idea already posted but I did not understand what you did not like about it. If you just want to focus on the first and last, not the third or something else, what is wrong with this? af,lf = genres.shift, genres.pop puts "#{af} is my absolute favorite" genres.each {|genre| puts "#{genre} is one of my favorites"} puts "#{lf} is my least fav. of all my favorites" Harry -- A Look into Japanese Ruby List in English http://www.kakueki.com/ruby/list.html