And I, mandatorily, will introduce my NameMagic here:
# first, gem install y_support
require 'y_support/name_magic'
class Person
include NameMagic
# here, Person receives for free the following functionality:
# * ability to use :name (alias :ɴ) named argument in the constructor
# * #name (alias #ɴ) instance method
# * #name= naming / renaming method
# * ability to name anonymous instances by merely assigning to constants
# * collection of both named and anonymous instances inside the namespace
# * hooks to modify the name, or do something else when the name is assigned
# * ability to specify a different namespace than mother class for instance collection
end
Joe = Person.new #=> #<Person:0xb7ca89f8>
Rick = Person.new #=> #<Person:0xb7ca57bc>
Joe.name #=> :Joe
Rick.ɴ #=> :Rick
Person.instances # [#<Person:0xb7ca89f8>, #<Person:0xb7ca57bc>]
Person.instance_names # [:Joe, :Rick]
Person.new name: "Kit" #=> #<Person:0xb9776244>
Person.instance_names #=> [:Joe, :Rick, :Kit]
p3 = Person.instance( :Kit ) #=> #<Person:0xb9776244>
p2 = Person.instance( "Rick" ) #=> #<Person:0xb7ca57bc>
# Also works if the argument is already a Person instance:
p1 = Person.instance( Person.instance( :Joe ) ) #=> #<Person:0xb9515ba8>
anon = Person.new #=> #<Person:0xb9955c54>
Person.instances.size #=> 4
Person.instance_names #=> [:Joe, :Rick, :Kit]
anon.name = :Hugo
Person.instance_names #=> [:Joe, :Rick, :Kit, :Hugo]
Person::Hugo #=> #<Person:0xb9955c54>
For concerns about garbage collection, one can forget the instances
Person.forget :Hugo #=> Returns, for the last time, "Hugo" instance
Person::Hugo #=> NameError
Person.forget_all_instances #=> [:Joe, :Rick, :Kit]
Person.instances #=> [] - everything is free to be GCed
Under the hood NameMagic uses the same approach as @sawa proposed (at least until const_assigned hook is provided by Ruby core devs), that is, searching whole ObjectSpace – but not for the instances of the mother object, but for the namespaces (Module class objects), whose constants are searched for the unnamed instances being assigned to them.