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

aronchick picture aronchick · Feb 11, 2010 · Viewed 26.4k times · Source

Ruby/Rails does lots of cool stuff when it comes to sugar for basic things, and I think there's a very common scenario that I was wondering if anyone has done a helper or something similar for.

   a = Array.new(5, 1)

   a.each_with_index do |x, i|
     if i == 0
       print x+1
     elsif i == (a.length - 1)
       print x*10
     else
        print x
     end
   end

Pardon the ugliness, but this gets at what one might want... is there a ruby way to do something to the first and last of a loop?

[EDIT] I think ideally this would be an extension on Array with parameters (array instance, all elements function, first elements function, last elements function)... but I'm open to other thoughts.

Answer

Matchu picture Matchu · Feb 11, 2010

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