Initializing an instance variable in Ruby

I think I'm a little alike when I try to understand instance variables in Ruby. My only goal here is to make sure that every object created for a given class has a variable with a given value without writing an initialize method for that class. Sort of:

 class Test @my = [] attr_accessor :my end t = Test.new t.my # I want [] but this shows nil 

Is it possible to achieve this without touching initialize ? Thanks.

EDIT: To clarify, I am writing a piece of code that will be executed similarly to attr_accessor in the sense that it will add an instance variable to the class in which it is executed. If I write my own initialize , I end up hiding what the user wrote.

+6
source share
3 answers

What you are doing is defining an instance variable at the class level (since classes are instances of the Class class, this works just fine).

And no, there is no way to initialize.

Edit: You have a slight misconception in your editing. attr_accessor does not add an instance variable to the class. Literally, this happens (using your my example):

 def my; @my; end def my=(value); @my = value; end 

It does not actively create / initialize any instance variable; it simply defines two methods. And you can well write your own class method that does similar things using define_method .

Edit 2:

To illustrate how to write such a method:

 class Module def array_attr_accessor(name) define_method(name) do if instance_variable_defined?("@#{name}") instance_variable_get("@#{name}") else instance_variable_set("@#{name}", []) end end define_method("#{name}=") do |val| instance_variable_set("@#{name}", val) end end end class Test array_attr_accessor :my end t = Test.new t.my # => [] t.my = [1,2,3] t.my # => [1, 2, 3] 
+11
source
 # as instance variable without initialize class Test1 def my; @my ||= [] end attr_writer :my end t = Test1.new t.my # as class instance variable class Test2 @my = [] class << self; attr_accessor :my end end Test2.my 
+2
source

I don’t think this is so, why do you hesitate to just write a quick initialization method?

0
source

Source: https://habr.com/ru/post/909896/


All Articles