DEV Community

gntorres
gntorres

Posted on

Self and Scope

The keyword "self" in Ruby always refers to the current object within that context. Self can be referenced to a class as well as an instance anime.rb - code [WSL_ Ubuntu] - Visual Studio Code 3_1_2021 9_41_54 PM (2)

Scope refers to the level of accessibility our variables have. Allowing our program to have different levels of scope allow certain variables to be accessed or referenced at different times. 3 types of scope would be local, instance, and class

Local
Refers to a variable that is declared within a method and cannot be accessed outside of said method anime.rb - code [WSL_ Ubuntu] - Visual Studio Code 3_1_2021 9_17_50 PM (2)

Class
Refers to variables that are accessed within all instances of our class. An easy way to detect a class variable is by the "@@" character next to our variable anime.rb - code [WSL_ Ubuntu] - Visual Studio Code 3_1_2021 9_20_57 PM (3)

Instance
Instance variables values are only used within specific instances of an object. Similar to our class variable we use a single "@" in order to declare our instance variable anime.rb - code [WSL_ Ubuntu] - Visual Studio Code 3_1_2021 9_20_57 PM (4)

Top comments (0)