class Var
@instance_variable = "instance variable"
@@class_instance_variable = "class instance variable"
def self.class_method
puts @instance_variable
puts @@class_instance_variable
end
def instance_method
puts @instance_variable
puts @@class_instance_variable
end
end
The class method has access to both class instance and instance variables. But the instance method has just access to class instance variable. @instance_variable is nil inside instance method. What is the logical explanation behind this?
Var.class_method #=> "instance variable" "class instance variable"
Var.new.instance_method #=> "class instance variable" nil
And is it correct that the instance variables dont get inherited by child classes? Why is that?
nilin shown result ofVar.new.instance_methodexecution is confusing, since it a) should appear before "class instance variable" and b) won’t appear at all inputs.class A; (@)(@)class_variable = 1; (@)class_instance_variable = 2; def my_method; (@)instance_variable = 3; end; end@instance_variableis nil inside instance method. What is the logical explanation behind this?” It was induced by the fact OP misunderstands the notion of instance variable scoping at all.