Notes posted by Rubybull
RSS feed
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]

0 thanks
Difference between enum#with_object and enum#each_with_object
I found a very good post on SO - which clearly explained the difference between enum#with_object and enum#each_with_object. The link is as follows:

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