Search code examples
rubyexceptionconstructor

Ruby Constructors and Exceptions


New to Ruby, and I'm trying to figure out what idiom to use to restrict some integer values to the constructor of a class.

From what I've done so far, if I raise an exception in initialize(), the object is still created but will be in an invalid state (for example, some nil values in instance variables). I can't quite see how I'm supposed to restrict the values without going into what looks unnecessarily big steps like restricting access to new().

So my question is, by what mechanism can I restrict the range of values an object is instantiated with?


Solution

  • Huh, you are entirely correct that the object still lives even if initialize raises an exception. However, it will be quite hard for anyone to hang on to a reference unless you leak self out of initialize like the following code I just wrote does:

    >> class X
    >>   def initialize
    >>     $me = self
    >>     raise
    >>   end
    >>   def stillHere!
    >>     puts "It lives!"
    >>   end
    >> end
    => nil
    >> t = X.new
    RuntimeError: 
        from (irb):14:in `initialize'
        from (irb):20:in `new'
        from (irb):20
    >> t
    => nil
    >> $me
    => #<X:0xb7ab0e70>
    >> $me.stillHere!
    It lives!