DEV Community

Mary Webby
Mary Webby

Posted on

Instance Method Review

Composing methods to build more powerful methods

  • In ruby, we use the def keyword within the class definition to add new methods to a class
class Person
  def say_hi
    return "Hello!"
  end
end
Enter fullscreen mode Exit fullscreen mode
  • the say_hi comes immediately after the def keyword, Ruby knows we are defining an instance-level method.

  • Every method’s main job is returning a value

  • Our programs are essentially just a long sequence of methods being called on the return values of previous methods, until we arrive at our desired output.

The self keyword

class Person
  attr_accessor(:first_name)
  attr_accessor(:last_name)

  def full_name
    assembled_name = self.first_name + " " + self.last_name

    return assembled_name
  end

  def full_name_caps
    return self.full_name.upcase
  end
end

rb = Person.new
rb.first_name = "Raghu"
rb.last_name = "Betina"

pp rb.full_name_caps
Enter fullscreen mode Exit fullscreen mode
  • self as a special variable that holds whatever object is at the forefront of Ruby’s mind when it is evaluating a program. Whatever line of code it is reading, whatever object is it working on at the moment, that is what self contains.

  • self represents the instance of the class that the method will be called upon in the future, formally, this object is known as the receiver of the message that is the method invocation.

Defining "association accessors"

  • Whenever you see Director#filmography, that is the Director class, and there is a filmography instance method within it.

Top comments (0)