Ruby | Enumerator each_with_index function

The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object.

Syntax: A.each_with_index
Here, A is the initialised object.

Parameters: This function does not accept any parameters.



Returns: the value of the given object.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Initialising an array and calling each_with_index function
[5, 10, 15, 20, 25, 30].each_with_index do |num, idx|
      
# Getting the values of the array    
  puts "#{num}"
  if ((idx) % 2 == 0)
    puts "end of line" 
  end 
end 

chevron_right


Output:

5
end of line
10
15
end of line
20
25
end of line
30

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Initialising an array and calling each_with_index function
[5, 10, 15, 20, 25, 30].each_with_index do |num, idx|
      
# Getting the values of the array    
  puts "#{num}"
  if ((idx + 1) % 2 == 0)
    puts "end of line" 
  end 
end 

chevron_right


Output:

5
10
end of line
15
20
end of line
25
30
end of line


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.