Ruby | Enumerable each_with_index() function

The each_with_index() of enumerable is an inbuilt method in Ruby hashes the items in the enumerable according to the given block. In case no block is given, then an enumerator is returned.

Syntax: enu.each_with_index { |obj| block }

Parameters: The function takes the block which is used to initialise the index to the individual objects.



Return Value: It returns the enumerator, if no block is given, else it hashes the items.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for each_with_index method in Enumerable
  
# Initialize 
hashing = Hash.new
enu = [7, 9, 10]
  
  
enu.each_with_index { |item, index|
  hashing[item] = index
}
  
# prints hash
puts hashing

chevron_right


Output:

{7=>0, 9=>1, 10=>2}

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for each_with_index method in Enumerable
  
# Initialize 
hashing = Hash.new
enu = [7, 9, 10]
  
  
enu.each_with_index

chevron_right


Output:

Enumerator: [7, 9, 10]:each_with_index


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.