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)?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With