From: Brian Candler Date: 2011-02-28T06:55:07+09:00 Subject: Re: Ensuring uniqueness of an object at creation time Abinoam Jr. wrote in post #984287: >> There's no need to do that. You could just raise an exception from >> within the initialize method. > > Person#initialize is called by Person.new > The Person.allocate is called _before_ Person#initialize. > > So, if I raise an exception at initialize point the object was already > allocated. Yes, but it will be garbage-collected later. > So, I don't want to raise an exception, I just want to return the > existing object without even allocating a new one. Then you could make a class method: class MyClass @all_objects = {} # non-threadsafe version def self.create(args) return @all_objects[args] if @all_objects[args] @all_objects[args] = new(args) end end > a = :prepare_b > b = :prepare_b > > With Symbol, if it has the same value, it's the SAME Symbol, not > different ones. > > a = "prepare_b" > b = "prepare_b" > > With String, even if they have the same value, they are different > objects. That's correct. And normal objects are like String; Symbol is very much a special case, baked into the language, to give efficient method dispatch. Why is it important in your application for your objects to have the singleton behaviour like Symbol? What bad things would happen if there were two objects representing the same message? Regards, Brian. -- Posted via http://www.ruby-forum.com/.