method
each_with_index
v1_9_1_378 -
Show latest stable
-
1 note -
Class: Enumerator
- 1_8_6_287
- 1_8_7_72
- 1_8_7_330
- 1_9_1_378 (0)
- 1_9_2_180 (-23)
- 1_9_3_125 (38)
- 1_9_3_392 (0)
- 2_1_10 (0)
- 2_2_9 (0)
- 2_4_6 (0)
- 2_5_5 (0)
- 2_6_3 (0)
- What's this?
each_with_index()
public
Iterates the given block for each element with an index, which start from 0. If no block is given, returns an enumerator.
Register or
log in
to add new notes.
Rubybull -
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]