It is impossible. First, Klass.new
will be created. Then, a local variable jacksaw
will be assigned to it. At the moment of the creation of the instance, it cannot tell what local variable it will be assigned to.
Determining name of variable referencing new instance inside initialize
-
24-09-2022 - |
Question
I can have a class announce its name whenever an instance is created like:
class Klass
def initialize
puts "#{self.class} instance created"
end
end
instance = Klass.new #=> Klass intance created
How can I have the instance name announced from the class initializer? something like:
class Klass
def initialize
puts "#{self.class} instance #{self.instance} created"
end
end
jacksaw = Klass.new #=> Klass instance "jacksaw" created
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow