How to act differently on the 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)?


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.


Using each_with_index, as others have described, would work fine, but for the sake of variety here is another approach.

If you want to do something specific for the first element only and something general for all elements including the first, you could do:

# do something with my_array[0] or my_array.first
my_array.each do |e| 
  # do the same general thing to all elements 
end

But if you want to not do the general thing with the first element you could do:

# do something with my_array[0] or my_array.first
my_array.drop(1).each do |e| 
  # do the same general thing to all elements except the first 
end

Arrays have an "each_with_index" method which is handy for this situation:

my_array.each_with_index do |item, i|
  item.do_something if i==0
  #common stuff
end

What fits best is depending on the situation.

Another option (if you know your array is not empty):

# treat the first element (my_array.first)
my_array.each do | item |
   # do the common_stuff
end

each_with_index from Enumerable (Enumerable is already mixed in with Array, so you can call it on an array without any trouble):

irb(main):001:0> nums = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):003:0> nums.each_with_index do |num, idx|
irb(main):004:1* if idx == 0
irb(main):005:2> puts "At index #{idx}, the number is #{num}."
irb(main):006:2> end
irb(main):007:1> end
At index 0, the number is 1.
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]