Search code examples
rubyclass-designscopeclass-variables

Can I initialize a class variable using a global variable? (ruby)


Do I have create extra method for this kind of assignment? @@variable = @global_variable Why? I want to have some variables that hold values and definitions to be accessible all through my script and have only one place of definition.

@global_variable = 'test'

class Test

@@variable = @global_variable

  def self.display
    puts @@variable
  end
end

Test.display #gives nil

Solution

  • In Ruby, global variables are prefixed with a $, not a @.

    $global = 123
    
    class Foo
        @@var = $global
        def self.display
            puts @@var
        end
    end
    
    Foo.display
    

    correctly outputs 123.

    What you've done is assign an instance variable to the Module or Object class (not sure which); that instance variable is not in scope of the class you've defined.