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 @instworld
you are inside BooksController class (i.e. self
will return BooksController
. Weird thing in ruby is that classes are also objects (the are instances of class Class
) hence you in fact declares instance variable @instworld
for this particular instance of class Class
m not for instance of BooksController
.
You can check it really easily by declaring class method:
class A
# self here returns class A
@variable = 'class instance variable'
@@variable = 'class variable'
def initalize
# self here returns the instance
@variable = 'instance variable'
end
def self.test_me
# self here returns class A
@variable
end
def test_me
# self returns the instance
@variable
end
#class variable is accessible by both class and instance
def test_me2
@@variable
end
def self.test_me2
@@variable
end
end
A.test_me #=> 'class instance variable'
A.new.test_me #=> 'instance variable'
A.test_me2 #=> 'class variable'
A.new.test_me2 #=> 'class variable'