I would say that the second option makes sense. The first will not lead to an error, but the instance of the object is completely outdated and pointless. External variables are not visible within the class:
var = "string" class A var = A.new end puts var #=> string
There is no closure, the outer var
is different from the outer in the class. This means that your object is “lost” after creation and will no longer be accessible, and will ultimately obey the GC.
When you say that the first example “works,” working in this context means that you can call a method on a newly created object immediately after creating this object in the class area. But it is impossible to save this object as a reference for later use (without assigning class (instance) variables to it).
If you don’t need a link for later use, and you really want to perform such a “single snapshot” operation, it would be more idiomatic to use a class method that can be called without creating an instance of the object or to perform the necessary actions in initialize
if it what needs to be done with each instance.
source share