Flowdock
each_with_index() public

Same as Enumerator#with_index, except each_with_index does not receive an offset argument.

Show source
Register or log in to add new notes.
February 3, 2013 - (v1_9_3_125)
0 thanks

How does enum#each_index differ from enum#with_each_index ?

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]