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
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top