Ruby Object's Self
My first experience with object oriented programming came with
Java while I was coding in high school. I never learned Java properly, and it wasn’t until working with
C++ later on that I got a better understanding of the OOP paradigm.
In Ruby, OOP is implemented in a relatively straightforward way. Classes are defined with the keyword
class, which seems unremarkable until you start defining classes in
Here’s some sample ruby code defining a song class.
The attribute accessors define and give read/write access to instance variables - variables that are tied to each instance of the class. But in the initialize method, they’re referred to by the keyword
self is simply a way to refer to the instance itself. So for the actual song object that is created,
self.name refers to that specific song’s name.
self is being pushed onto the @@all class array, self is being used by itself to push that whole object onto the array.
self is also used to define class methods, methods that don’t aren’t a part of instances but the class itself. For example, self.all returns the @@all class array.
The idea of self-referential objects can be tricky if you’re just starting to learn OOP, but it’s necessary in order to build objects that can access their own data.
You can read more about
self in the Ruby docs.