views:

63

answers:

1

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
+7  A: 

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.

Mark Rushakoff
Actually the OP set the instance variable on the "main object".
sepp2k
@Mark Rushakoff: you're right. Thank you. Even `@@variable = @@global_variable` works.
Radek