Variables with @
are instance variables in ruby. If you're looking for class variables, they're prefixed with @@
, so you should be using @@my_var = 123
instead.
And the reason you can't use instance variables that way, is because if you define instance variables outside methods, they don't live in the same scope as your methods, but only live while your class is interpreted.
var1
in your example is a local variable, which will only be visible inside the index
method.
Examples:
class Foo
@@class_variable = "I'm a class variable"
def initialize
@instance_variable = "I'm an instance variable in a Foo class"
local_variable = "I won't be visible outside this method"
end
def instance_method_returning_an_instance_variable
@instance_variable
end
def instance_method_returning_a_class_variable
@@class_variable
end
def self.class_method_returning_an_instance_variable
@instance_variable
end
def self.class_method_returning_a_class_variable
@@class_variable
end
end
Foo.new
=> #<Foo:0x007fc365f1d8c8 @instance_variable="I'm an instance variable in a Foo class">
Foo.new.instance_method_returning_an_instance_variable
=> "I'm an instance variable in a Foo class"
Foo.new.instance_method_returning_a_class_variable
=> "I'm a class variable"
Foo.class_method_returning_an_instance_variable
=> nil
Foo.class_method_returning_a_class_variable
=> "I'm a class variable"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…