From: Eleanor McHugh Date: 2009-06-12T21:15:34+09:00 Subject: Re: Idiomatic way to detect first/last iteration? On 12 Jun 2009, at 12:45, paron wrote: > Is detection really what you want? Doesn't that imply that you test > each iteration? Since the array is ordered by definition, it seems > (needs tested!) that creating three entities might be faster. > > in helper: > def first_also_ran_last(records) > > first_record=records.shift > last_record=records.pop > > return [first_record, records, last_record] > end > > in view: > <% parsed_records = first_also_ran_last(@whatever) > <%="Really like #{parsed_records[0]}"%> > <% parsed_records[1].each do |also_ran|%> #(if any) > <%= "Sorta like #{also_ran}"%> > <%end -%> > <%unless parsed_records[2].nil?-%> > <%= "Don't much like #{parsed_records[2]}"%> > <%end-> > > Don't know if it's faster, or more idiomatic, but perhaps it's more > semantic? With a bit of tidying you can reduce the view further: def x records, message = "Nothing Relevant" # I can't think of a _good_ name for the method off-hand first = records.shift || message last = records.pop || message [first, records.empty? ? [message] || records, last] end <% track_listing = x records, "I don't have one!!!" %> <%= "My favourite track: #{track_listing.shift} %> <% track_listing.shift.each do |track| -%> <%= "Another track I like: #{track} %> <% end -%> <%= "The track I like least: #{track_listing.shift} %> Ellie Eleanor McHugh Games With Brains http://slides.games-with-brains.net ---- raise ArgumentError unless @reality.responds_to? :reason