fastruby / fast-ruby

:dash: Writing Fast Ruby :heart_eyes: -- Collect Common Ruby idioms.
https://github.com/fastruby/fast-ruby
5.67k stars 376 forks source link

each with index vs while loop returning different values #71

Closed michaelachrisco closed 9 years ago

michaelachrisco commented 9 years ago

From: https://github.com/JuanitoFatas/fast-ruby/blob/master/code/enumerable/each_with_index-vs-while-loop.rb In the example code, the return types are returning different objects and may be effecting the overall Benchmarking time. I came across this in another gem. I'll be adding code to see if this is true or not.

2.2.2 :001 > ARRAY = [*1..100]
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] 
2.2.2 :002 >   ARRAY.each_with_index do |number, index|
2.2.2 :003 >         number + index
2.2.2 :004?>     end
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] 
2.2.2 :005 >   index = 0
 => 0 
2.2.2 :006 >   while index < ARRAY.size
2.2.2 :007?>       ARRAY[index] + index
2.2.2 :008?>       index += 1
2.2.2 :009?>     end
 => nil 
michaelachrisco commented 9 years ago

The issue, I believe, is that each with index vs while are fundamentally different. The while loop is adding the ARRAY[index] + index and then returns nil whereas ARRAY.each_with_index adds the newly created index and the number then returns the initial array. If this test is to be identical, the return value needs to be the initial ARRAY.

I know this is a small nitpick but l will add in the PR anyway.

JuanitoFatas commented 9 years ago

:+1: