In inject or reduce method n represents the accumulated value; this means that the result of each iteration accumulates in the variable n . It can be, as in your example, a sum or a product of elements in an array.
yield returns the result of a block that is stored in n and used in the following iterations. This is what makes the result โcumulative.โ
a = [ 1, 2, 3 ] a.sum
Alternatively, to calculate the amount, you could also write a.reduce :+ . This works for any binary operation. If your method has the name symbol , the notation a.reduce :symbol matches the notation a.reduce { |n, v| n.symbol v } a.reduce { |n, v| n.symbol v } .
attr , and companies are actually methods. Under the hood, they dynamically determine the methods for you. It uses the character you pass to determine instance variable names and methods. :member leads to the @member instance @member and the member and member = methods.
The reason you cannot write attr_reader @member is because @member is not in itself and cannot be converted to a character; it actually tells ruby โโto get the value of the @member instance instance variable of the self object, which in the scope class is the class itself.
To illustrate:
class Example @member = :member attr_accessor @member end e = Example.new e.member = :value e.member => :value
Remember that access to undefined instance variables gives nil , and since the attr family of methods accepts only characters, you get: TypeError: nil is not a symbol .
As for Symbol , you can use them as strings. They make great hash keys because equal characters always refer to the same object, unlike strings.
:a.object_id == :a.object_id => true 'a'.object_id == 'a'.object_id => false
They are also commonly used to indicate method names, and can actually be converted to Proc s , which can be passed to methods. This allows us to write things like array.map &:to_s .
Check out this article for more interpretations of the symbol.