I\'m new to rails and ruby. I was studying the concept of class and instance variables. I understood the difference but when I tried it out using the controller in rails it got
When you declare instance variable outside of method, you might not get the result you want. It is an instance variable, yes, but it belongs to the class itself (which is an instance of class Class
).
class Foo
@myvar = "class-level"
def initialize
@myvar = 'instance-level'
end
end
f = Foo.new
f.class.instance_variable_get(:@myvar) # => "class-level"
f.instance_variable_get(:@myvar) # => "instance-level"
f.instance_variable_get(:@myvar2) # => nil
If you try to get value of uninitialized ivar, it will evaluate to nil
. That's why you got nil
in your experiments: the variable doesn't exist at that scope.
To get instance-level variables, set them in methods/actions.