The ruby class-instance stuff is giving me a headache. I understand given this...
class Foo @var = 'bar' end
...that @var
is a variable on the created class's instance.
But how do I create a sub-class overridable class variable?
Here is an example of what I would do in Python:
class Fish: var = 'fish' def v(self): return self.var class Trout(Fish): var = 'trout' class Salmon(Fish): var = 'salmon' print Trout().v() print Salmon().v()
Which outputs:
trout salmon
How do I do the same thing in ruby?
Class 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.
Re accessing instance/class variables (mainly from the console), for me it worked like FooClass. class_variable_set(:@@foo, 'bar') and FooClass. class_variable_get(:@@foo) , and for instances foo_class. instance_variable_set(:@foo, 'baz') and foo_class.
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.
What is the difference between class variables and class instance variables? The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.
To contrast @khelll's answer, this uses instance variables on the Class objects:
class Fish # an instance variable of this Class object @var = 'fish' # the "getter" def self.v @var end # the "setter" def self.v=(a_fish) @var = a_fish end end class Trout < Fish self.v = 'trout' end class Salmon < Fish self.v = 'salmon' end p Trout.v # => "trout" p Salmon.v # => "salmon"
Edit: to give instances read-access to the class's instance variable:
class Fish def type_of_fish self.class.v end end p Trout.new.type_of_fish # => "trout" p Salmon.new.type_of_fish # => "salmon"
@var
mentioned above is called class instance variable, which is different from instance variables... read the answer here to see the diff.
Anyway this is the equivalent Ruby code:
class Fish def initialize @var = 'fish' end def v @var end end class Trout < Fish def initialize @var = 'trout' end end class Salmon < Fish def initialize @var = 'salmon' end end puts Trout.new.v puts Salmon.new.v
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