Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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)?

like image 372
Panagiotis Panagi Avatar asked Nov 18 '11 11:11

Panagiotis Panagi


People also ask

What is the simplest way to iterate through the items of an array Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

What does .each do in Ruby?

The each() is an inbuilt method in Ruby iterates over every element in the range. Parameters: The function accepts a block which specifies the way in which the elements are iterated. Return Value: It returns every elements in the range.

What does .times do in Ruby?

The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead.


2 Answers

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.

like image 56
detunized Avatar answered Sep 17 '22 15:09

detunized


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 
like image 44
Russell Avatar answered Sep 21 '22 15:09

Russell