From: Luc Heinrich Date: 2002-04-05T02:48:01+09:00 Subject: Re: Test the result of an initialization ? On 4/04/2002 18:52, "Jayce Piel" wrote: > By putting begin/rescue code around all call to #new, the code begins to > be unreadable... Uh, that's highly debatable, but I won't bite (at least not here)... ;-) Anyway, if you *really* want to use the 'return-nil-on-error' creation pattern, why don't you use a factory method in your class ? Like... class ArchiveFile private_class_method :new def ArchiveFile.create( name ) return new(name) if (name.is_valid_and_stuff?) return nil end ... end ...and then do... foo = ArchiveFile.create( "/hoink/gruik/woof/archive.tar" ) if foo.nil? puts "Crap!" else foo.do_something_useful foo.close end ...which *really* looks ugly, if you ask me. A much better way to do that would be to take the Ruby way (of course) and use the open-with-block style, like that: class ArchiveFile private_class_method :new def ArchiveFile.open( name ) if (name.is_valid_and_stuff?) archive_file = new( name ) yield( archive_file ) archive_file.close end end ... end ...and then do... ArchiveFile.open( "/hoink/gruik/woof/archive.tar" ) do |archive_file| archive_file.do_something_useful end ... which: 1. Ensure that the block is executed *only* if the parameter is valid. 2. Automatically close the archive file when the block ends. 3. Looks much nicer... :-) Depending on what you want, this might be a better solution. And on a more general note, you really shouldn't try to apply patterns or idioms from other languages when Ruby have a specific (and usually better :-) ) approach. -- Luc - lucsky@mac.com