If I have a class with an attr_accessor
, it defaults to creating an instance variable along with the corresponding getters and setters. But instead of creating an instance variable, is there a way to get it to create a class variable or a class instance variable instead?
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.
Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.
In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data. We say that objects can: Do things.
In Ruby, object methods are public by default, while data is private. To access and modify data, we use the attr_reader and attr_writer . attr_accessor is a shortcut method when you need both attr_reader and attr_writer .
Like this:
class TYourClass class << self attr_accessor :class_instance_variable end end
You can look at this as opening the metaclass of the class (of which the class itself is an instance) and adding an attribute to it.
attr_accessor
is a method of class Class
, it adds two methods to the class, one which reads the instance variable, and other that sets it. Here's a possible implementation:
class Class def my_attr_accessor(name) define_method name do instance_variable_get "@#{name}" end define_method "#{name}=" do |new_val| instance_variable_set "@#{name}", new_val end end end
Completely untested class attribute accessor:
class Class def class_attr_accessor(name) define_method name do class_variable_get "@@#{name}" end define_method "#{name}=" do |new_val| class_variable_set "@@#{name}", new_val end end end
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