Composing methods to build more powerful methods
- In ruby, we use the
defkeyword within theclassdefinition to add new methods to a class
class Person
def say_hi
return "Hello!"
end
end
the
say_hicomes immediately after thedefkeyword, 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
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.
selfrepresents 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 theDirectorclass, and there is afilmographyinstance method within it.
Top comments (0)