"A class variable (@@) is shared among the class and all of its
descendants. A class instance variable (@) is not shared by the class's
descendants."
There's a trend of using (class) instance variables most of the time and to
use class variables _only_ when you really need to share state between
descendants.
I didn't understand the "initialization" part.
Could you give one example where you would like to do so?
Best regards,
Abinoam Jr.
···
On Fri, May 20, 2016 at 10:16 PM, A Berger <aberger7890@gmail.com> wrote:
Hello,
What is this @x ?
Wondering why that is allowed -- @objectvar of class is not the same as @@classvar of objects...
class A
@x=1
def A.b; @x+=1; end
end
p A.b
How can a class best being initalized?
class A
def self.initialize; p "started" end
end
# How to start it? (don't want to explicitely call A.initialize) ?
Thats why I'm asking how @x is behaving inside a class (as in example) -
where is it stored? Which variable is this of? (Why no error?)
If you do `@var = value` then you always set the instance variable `@var`
on the object referenced by `self`. In the class body `self` references the
class object.
class Person @count = 0
end
Person.instance_variable_get("@count") # => 0
For an object we call X.new
to run the #initialize() ,
what can be done to run .initialize of a class ?
`#initialize` is called by `.new`. If you want to initialize class instance
variables then I'd do it in the body. There's no class-level `.initialize`
that'd be called automatically as there's no need for one. When you define
a class then you do have an object you want to initialize. When you define
`#initialize` there's still no object to initialize: you first define the
class and then use the class to create instances.
···
--
Greg Navis
I help tech companies to scale Heroku-hosted Rails apps.
Free, biweekly scalability newsletter for SaaS CEOs
<http://www.gregnavis.com/newsletter/>