I typed following code in irb:
(1..5).reduce([]){|a,b| p a,b }
Expected results would be:
[]
1
[]
2
[]
3
[]
4
[]
5
=> []
Since I did not modify a at any point return value of inject would be []
But for strange reason I get this:
[]
1
[[], 1]
2
[[[], 1], 2]
3
[[[[], 1], 2], 3]
4
[[[[[], 1], 2], 3], 4]
5
=> [[[[[[], 1], 2], 3], 4], 5]
Why is the return value of inject modified from initial when I did not even change it ? Could someone please throw some light on it.
I am using MRI 1.9.2
Thanks
Enumerable#reduce does the following: it iterates over each element in enumerable and pass it as second parameter of the block. The first parameter is the value returned by the block for the previous item.
reduceargument ([]in your case) is passed as the first block parameter for the first block call only (it is called initial value in the documentation).pprints the result and returns value of its arguments. This value is passed to the next block call as a first argument becausepcall is the last expression in the block and it is considered the return value of this block.In order to get expected result return first argument of the block from your block: