class MainController < ApplicationController
@my_var = 123
def index
var1 = @my_var
end
def index2
var2 = @my_var
end
end
Why is neither var1
no var2
equal to 123
?
A class variable belongs to the class, not the object. You declare a class variable using two @signs for example, @@name. We can, for example, keep count of all person objects created using a class variable.
Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
What's an instance variable? In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.
class . There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With