DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on • Updated on

Scope and Self in Ruby

Ruby was my first step to the coding world. I fell in love with the simplicity and clarity of its syntax, and after that, all I wanted to do was code. But despite how easy Ruby seems, there are some concepts where it can get confusing.


Self was one of those concepts. But in order to understand self, we need to understand what scope is. Depending on the scope in which self is being used, self can refer to different objects.

When writing code, we use the variables, objects, and methods available to us, and call them within the code. These variables, objects, and methods have varying levels of accessibility. This is what we call the Scope. Scope is also available in other programming languages. In Ruby there are 2 types of basic scope: Global Scope and Local Scope.

Global Scope - it is the scope that contains and is visible in all other scopes. A variable assigned in Global Scope can be accessed from anywhere in the file. These Global Variables begin with $. Be aware that using Global Variables is not always a good idea because they can kill the flexibility and extensibility of your program. Many programmers try to avoid using them as much as possible.

Local Scope - If a variable is assigned in a method, its scope is called Local Scope. The assigned variable is therefore called a Local Variable. The Local Variable is not accessible outside the method because it is bound to the method context in which it is declared.

           $i_am_global_variable = "I can be accessed from anywhere"

           def method_name
            i_am_local_variable = "I am not accessible outside this method"

Self always refers to only one object in a particular place in the program, but depending on that place, the object may be different. After determining which object self refers to, we can understand what scope of the program we are in:

  1. When Self is inside the scope or method of a class, it refers to that class.
  2. In the scope of a method that does not belong to the class, self refers to the object from which this method is called.
  3. Self inside the scope of an instance method will refer to the particular instance of the class from which it is called. Note: initialize method in the class is also an instance method.
         class Song
             attr_accessor :name
             def initialize(name)
                @name = name

             def self.method_name
                puts "Self inside class method is: #{self}"

             def method_name
               puts "Self inside instance method is: #{}"

          hello ="Hello")
          Song.method_name     #Self inside class method is: Song          
          hello.method_name    #Self inside instance method is: Hello

Top comments (0)