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?
Huh, you are entirely correct that the object still lives even if
initializeraises an exception. However, it will be quite hard for anyone to hang on to a reference unless you leakselfout ofinitializelike the following code I just wrote does: