From: Robert Klemme Date: 2010-01-09T05:15:14+09:00 Subject: Re: ruby constructor return value? On 01/08/2010 12:39 PM, I V wrote: > On Thu, 07 Jan 2010 15:13:30 -0500, Thom Wharton wrote: >> Basically, I am trying to get new to return nil if construction of the >> object fails. I have a strong background in C++ coding, and one thing >> that has always irked me about the language is that constructors cant >> fail -- the object is always created regardless of whether or not it can >> be properly constructed. > > I'm not sure what you mean here. In both C++ and Ruby, constructors can > fail - they do so by raising an exception - and, if they do fail, no > object is created. That's not true: the object is created and then will be GC'ed. You can easily demonstrate it: robert@fussel:~$ ruby19 f.rb [83760838, false] [83760376, true] f.rb:9:in `initialize': Constructor error (RuntimeError) from f.rb:14:in `new' from f.rb:14:in `
' 83760376 83760838 robert@fussel:~$ cat f.rb class X def self.g(x) ObjectSpace.define_finalizer(x) {|id| puts id} end def initialize(fail = false) p [object_id, fail] X.g(self) raise "Constructor error" if fail end end X.new X.new true robert@fussel:~$ There is no other alternative to this approach. The instance is *always* created. It's only that you typically do not leak self from #initialize and so in case of exceptions nobody has a reference to the object and hence it is unusable. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/