Rubbish collection of class instance variables in ruby

If I use a type method

def self.get_service_client return @service_client if !@service _client.nil? @service_client = #initialize logic end 

Now @service_client is an instance variable of the class. What is the time in memory? Can I not reinitialize a bank to it while the class is in memory (for example, a static variable)?

+6
source share
1 answer

Classes are also instances in Ruby, but when you define a class in the usual way, it is assigned to a constant, and this constant refers to other constants, preventing its collection. Thus, the class will be in memory indefinitely. Since the class will remain in memory, the class instance variable will also be, since the class (which is an instance of the object) maintains a reference to its instance variables.

Aside, the idiomatic way to do this is:

 def self.get_service_client @service_client ||= initialize_service_client end 
+10
source

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


All Articles