If I am editing the Array class, shouldn't I have to define each method with a self (e.g. self.sum). I'm not sure why this passes the rpsec tests for the 'Test-First' Ruby track without the self.method immediately following the def.
class Array
def sum
count = 0
self.each {|x| count += x}
count
end
def square
self.map {|x| x * x}
end
def square!
self.map! {|x| x * x}
end
end
These are "instance methods" - they operate on an instance of an
Array, not theArrayclass itself. If you were to putself.before the name of each method when defining it, you would be defining a "class method", which wouldn't make any sense for these methods.Although not necessary, the reason that
self.works when invoking these methods from within the body of another one of the methods is thatselfis defined to be the "instance" at that point. This contrasts to when you're defining the methods withdef, whereselfis theArrayclass.