From: Thomas Hurst Date: 2008-04-03T08:29:28+09:00 Subject: Re: ruby constructor return value? * 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. -- Thomas 'Freaky' Hurst http://hur.st/