Not understanding a code which uses each without an object


#1

class Array
def inject(n)
each { |value| n = yield(n, value) }
n
end
def sum
inject(0) { |n, value| n + value }
end
def product
inject(1) { |n, value| n * value }
end
end
[ 1, 2, 3, 4, 5 ].sum
»
15
[ 1, 2, 3, 4, 5 ].product
»
120

In the inject method, I don’t understand what the ‘each’ is doing, it doens’t have an object to perform iteration
I am reading an book for ruby, this is where I came up with this problem.
Here’s the link to that book.
Note: It’s in PDB format you might have to convert to PDF.
Chapter name is containers,block and iterators


#2

They have opened the array class and written the inject method directly in it. Each is a method written in the array class which iterates over self, in this case self is implicitly the array you call inject on.


#3

Thanks I got it now !!