Rey T
2 min readFeb 17, 2021

--

What is the scope in Ruby?

And why is it an important concept in programming.

Variables can be defined as place-holders and can be used to store data. Variables serve as a way of identifying data. For example, we can set name = x_variable. When name is called, x_variable will be returned because that is the piece of data that is being stored. This would allow for cleaner, safer code due to not having to rewrite the same code but instead just reference the variable.

Local variable, Instance variable, Class variable and Global variable are variables used in Ruby and they are differentiated based on their scope. What exactly does scope refer to in regards to programming? Scope refers to where a variable can be access, in other words where is it visible. Therefore, scope = accessibility. Let’s take a look at how we are able to identify these variable types and define their scope. The variables are listed below based on their accessibility, beginning with the variable with the least accessibility.

Local variable: x_variable: x_ variable has the least accessibility out of the four variables. It can only be accessed in a specific, local environment, hence it’s name “local variable”. It’s scope is inside a specific method and therefore can only be access inside that specific method. If it is defined in one method, then it cannot be accessed by another method.

Instance variable: @x_variable: Instance variable has a bit more accessibility compared to Local variable due to the addition of the single @ symbol. It can be accessible in any instance method within the instance of a class. Instance variables belong to the instance. They are commonly found in the initialized method because you are creating new instances and then setting the property, therefore the instance variables belong to each one of the new instances that were created; for example, @x_variable = x_variable. Instance variable allow the data to exist outside of the initialized method and allows all of the method within the same class to utilize the store data.

Class variable: @@x_variable: Class variable has two @ symbols at the beginning of it’s name and has the 2nd greatest accessibility out of the four variables. Class variables belong to the class, therefore its scope is anywhere inside the class; meaning being accessible to the entire class. A common class variable is @@all = [].

Global variable: $x_variable — The Global variable has a $ symbol at the beginning of the name. This variable has the greatest accessibility among the four variables because it has a global scope and can be access anywhere in the file.

--

--