Kim Mens
Kim Mens

Reputation: 335

What is the difference in scoping between a global variable and a constant in Ruby?

In the Ruby programming language there is both the notion of a global variable, which start with a dollar sign, for example $foo and a constant which starts with a capital, for example Foo. What is the exact difference in scope of each of these two kinds of names in Ruby, and in what particular case should a global variable be preferred over a constant, or vice versa?

Upvotes: 1

Views: 219

Answers (1)

rkalra
rkalra

Reputation: 375

Global variables are the ones that can be accessed from anywhere. Their scope turns to be the whole of the main object. This means they can be used anywhere in this scope i.e anywhere in the code itself. For instance

module A
  module B
    class C
      $glo = 'this is glo-bal variable'
    end
  end
end

module D
  class E
    CON = 'this is con-stant'
    def call_glo
      puts $glo
    end

    def call_con
      puts CON
    end
  end

  def self.call_con
    puts CON
  end

  E.new.call_glo                 #=> "this is glo-bal variable"
end

D::E.new.call_glo                #=> "this is glo-bal variable"
D::E.new.call_con                #=> "this is con-stant"
D.call_con                       #=> Throws Error Unitialized Constant

While the constants are restricted to the scope they are defined in. They can only be used in the scope they are defined.

Now, as you said Constants starts with capitals, hence all the class names and module names are themselves nothing but Constants.

Now in the above example, you see the call_glo method is called twice. Once from the scope of module D while one from the main object scope, do you see the difference between the instantiation of class E?

In module D it is called without any scope operator :: while outside of module we had to use the scope operator, that is the restriction of scope. Constants are bound to.

Upvotes: 2

Related Questions