I’m reading through ‘the ruby programming language’ and have come across the following piece of code.
a.inject do | sum, x |
sum + x
end
I understand that x contains one element from a that will be passed to the bock but the ‘sum’ part is confusing me, is it some kind of operator or function or is it just another variable like x. I understand that the x variable could be called f, or v but if thats the case how does ruby know that x is that variable to pass the element to the iterator in, surly it could just as easily pass the variable into sum (if it is even a variable).
I hope that makes sense, as always I’m finding it had to put my confusion into works as if I understood the nature of the problem better I would be more likley to be able to find my own solution.
Thanks!
sum is the accumulator object, for example the following code:
The above code is the same as:
You can give the accumulator object any valid variable name, of course better with a meaningful name in the context.