Magic First and Last Indicator in a Loop in Ruby/Rails?

Solution 1:

You could grab the first and last elements and process them differently, if you like.

first = array.shift
last = array.pop
process_first_one
array.each { |x| process_middle_bits }
process_last_one

Solution 2:

If the code for the first and last iteration has nothing in common with the code for the other iterations, you could also do:

do_something( a.first )
a[1..-2].each do |x|
  do_something_else( x )
end
do_something_else_else( a.last )

If the different cases have some code in common, your way is fine.