From: Matthew Smillie Date: 2006-07-28T04:46:55+09:00 Subject: Re: Prevent class instantiation from the initialize method? On Jul 27, 2006, at 20:21, Dave Mihalik wrote: > > Can some show me how to implement this java program using Ruby? > I am simply trying to prevent the testclass from being instantiated in > the constructor. > I am then checking to see if the the class has instanatiated properly. > > [Java.elide()] > > I am new to Ruby but this is what I have so far: > > class Testclass > def initialize() > > raise "Instantiation cancelled." > > end > end > > begin > > mytest = Testclass.new() > > rescue Exception => e > begin > > puts e > exit 1 > > end > > puts "Instantiation not cancelled." > > > end > > If the raise line in the initialize method is disabled, the puts > "Instantiation not cancelled." line does not execute. Because it's always going to execute that inner begin...end block. I expect you want something more like the following: begin mytest = Testclass.new rescue Exception => e puts e exit 1 end puts "Instantiation not cancelled" The first 'begin' starts the protected block, similar to Java's try { ... }, and the 'rescue' acts on any exceptions raised within that block. That said, using exceptions for control flow is usually a bit of pathological case in Ruby, and there's usually a better way to accomplish the same result. The two possible answers that spring to mind are (simple) making the initialiser private or (slightly more complicated) just removing the new method all together: class Testclass class << self undef_method :new end end my_test = Testclass.new() NoMethodError: undefined method `new' for Foo:Class from (irb):6 from :0 matthew smillie.