Reputation: 576
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
Upvotes: 1
Views: 53
Reputation: 168269
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.
Upvotes: 4