with_index(p1 = v1) public

Iterates the given block for each element with an index, which starts from offset. If no block is given, returns an enumerator.

Show source
Register or log in to add new notes.
February 2, 2013 - (v1_9_3_125)
1 thank

Enumerator#with_index has confusing documentation

Enumerator#with_index has confusing documentation, but hopefully this will make it clearer.

Code example

a=[11,22,31,224,44].to_enum
=> [11, 22, 31, 224, 44]
a.with_index { |val,index| puts "index: #{index} for #{val}" }
index: 0 for 11
index: 1 for 22
index: 2 for 31
index: 3 for 224
index: 4 for 44

a=[11,22,31,224,44].to_enum
=> #<Enumerator: [11, 22, 31, 224, 44]:each>
a.with_index(2){ |val,index| puts "index: #{index} for #{val}" if val > 30 }
index: 4 for 31
index: 5 for 224
index: 6 for 44
=> [11, 22, 31, 224, 44
March 5, 2013
0 thanks

Minor correction to Rubybull's examples?

Was your first example intended to be:

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