Finding (my)self in .class

Welcome to my first blog post as a student at the Flatiron school.

Since I just started classes here, I’ve been having a lot of memories about when new programs started and a new cohort of educators would arrive at my last job (I worked for an outdoor education center). On the first day of one fall season, I felt like I really started off on the wrong foot with the person I was training. When I later apologized to her, she said that from her perspective it had gone great.

Similar to the way my self-perception of this moment changed from when I was just inside my own head to when I was able to get an outside perspective, the ‘self’ method functions differently when it’s inside and outside of a method.

When self is used to call a method or return or alter an instance variable INSIDE a method, it is only able to access to data pertaining to its own instance. It is referring to itself in singular, and in specific — that particular instance.

In the example below, self is used to call the name getter method to return the name of that particular instance.

def say_name
"My name is #{}."

This same word, self, is understood differently when it is used in the context of a method definition or when calling variables and methods from inside a method.

When self is used in the method DEFINITION, it gives the class access to variables pertaining to all instances of the class. ‘Self’ now can be called by the class, in order to learn about and aggregate information relating to all of the specific instances. In this way, it also lets me know that the use of it INSIDE that method now refers to the class. ie

def self.create
picasso ="pablo picasso")
@@all_artists << picasso

This method (above) is a class method that creates new instances of artists. The use of self in the definition indicates that self.create is the same as Artist.create.

So why would I ever need .class? I didn’t understand why I would write something where ‘self’ wouldn’t help me. I learned that when an individual instance needs access to a class variable, however, .class can provide it.

def save 
self.class.all << self

Here, .class is allowing the instance of artist (made apparent by the use of “self” inside the metho) to access and alter the class variable @@all (which is an array). It would otherwise only be accessible at the class level, such that it would have to be called by Artist.all to get all instances of artist. Instead using .class allows self, to add itself to the array as an instance of an Artist so that later the class will have a record of it.

Thanks for reading my first post!


self — can refer to both the class as a whole and an individual instance of the class, depending on where it is present, and can be deduced from the clues the method name provides

.class — this is the inverse of using self in the method definition. it all allows the instance to have access to data that is stored at the class level.