rubyrspecclass-methodtest-first

Editing Class methods def self.xxx


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

Solution

  • These are "instance methods" - they operate on an instance of an Array, not the Array class itself. If you were to put self. 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 that self is defined to be the "instance" at that point. This contrasts to when you're defining the methods with def, where self is the Array class.