Panagiotis Panagi Panagiotis Panagi - 2 months ago 7
Ruby Question

How to act differently on first iteration in a Ruby loop?

I always use a counter to check for the first item (

i==0
) in a loop:

i = 0
my_array.each do |item|
if i==0
# do something with the first item
end
# common stuff
i += 1
end


Is there a more elegant way to do this (perhaps a method)?

Answer

You can do this:

my_array.each_with_index do |item, index|
    if index == 0
        # do something with the first item
    end
    # common stuff
end

Try it on ideone.