Pregunta

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
¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top