method

each_with_index

v1_9_3_125 - Show latest stable - Class: Enumerator
each_with_index()
public

Same as Enumerator#with_index(0), i.e. there is no starting offset.

If no block is given, a new Enumerator is returned that includes the index.

1Note

How does enum#each_index differ from enum#with_each_index ?

Rubybull ยท Feb 3, 2013

==== Here is the working one each_with__index:

 a=[11,22,31,224,44].each_with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
   index: 0 for 11
   index: 1 for 22
   => [11, 22, 31, 224, 44]

Below couldn't produce the output, as with_index couldn't work on the array.To make it workble, we need to first convert it to enumerator. And that can be done via the help of .to_enum, .each, or .map

 a = [11,22,31,224,44].with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
 =>NoMethodError: undefined method `with_index' for [11, 22, 31, 224, 44]:Array
        from (irb):2
        from C:/Ruby193/bin/irb:12:in `<main>'
	

==== Here is the working one with_index:

 a = [11,22,31,224,44].each.with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
 index: 0 for 11
 index: 1 for 22
 => [11, 22, 31, 224, 44]