From: Thom Wharton Date: 2010-01-08T05:13:30+09:00 Subject: Re: ruby constructor return value? Thomas Hurst wrote: > * Brendan Stennett (brendan6@gmail.com) wrote: > >> if o = Zip.new('00000') >> //this block execute whether or not that zip code exists >> else >> //never happens >> end > > Normally you'd use an exception; e.g. make a ZipCodeNotFound class > inherited from StandardError and rescue it. You could even do: > > o = Zip.new(..) rescue nil > > And this will rescue the exception and return nil. It will also eat any > other StandardError, so beware. If you want users of the class to be > able to just check for nil/false, make a factory method: > > class Zip > def self.find(zip) > new(zip) > rescue ZipCodeNotFound > false > end > end > > o = Zip.find('..') > > However, new is just a method like any other; you can override it if you > really want it to potentially return nil: > > class Zip > def self.new(*args) > o = allocate > if o.__send__(:initialize, *args) > return o > else > return nil > end > end > end > > Allocate will make a new object without calling the constructor, you can > then call initialize yourself (using __send__ as it's a private method) > and conditionally return your new object. > > Since this may be surprising behavior for .new I don't really recommend > it, though. Is this info still valid? More specifically, would I have to create a new method for my class to have it return nil? And would my class initializer method have to raise an exception or could it return nil if the construction fails? 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. Btw, I've noticed that the File class will return nil if you call the new method with a filename that doesnt refer to an existing file. Does the File class have its own new/initialize methods? If so, is that code available online for examination? Thanks, Thom -- Posted via http://www.ruby-forum.com/.