From: Harry Kakueki Date: 2009-06-12T21:45:47+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. > > Or how about something like this? fav = Hash.new(" is one of my favorites") fav[0] = " is my absolute favorite" fav[genres.length-1] = " is my least fav. of all my favorites" puts genres.zip(Array.new(genres.length){|i| fav[i]}).map{|x| x.join} Harry -- A Look into Japanese Ruby List in English http://www.kakueki.com/ruby/list.html