After I have created a serious bunch of classes (with initialize methods), I am loading these into IRb to test each of them. I do so by creating simple instances and calling their methods to learn their behavior. However sometimes I don’t remember exactly what order I was supposed to give the arguments when I call the .new method on the class. It requires me to look back at the code. However, I think it should be easy enough to return a usage message, instead of seeing:
ArgumentError: wrong number of arguments (0 for 9)
So I prefer to return a string with the human readable arguments, by example using “puts” or just a return of a string. Now I have seen the rescue keyword inside begin-end code, but I wonder how I could catch the ArgumentError when the initialize method is called.
Thank you for your answers, feedback and comments!
It is possible to hook into object creation by overriding the
Class#newmethod e.g.This overriden method calls the normal
newmethod but catchesArgumentErrorand if the class of the object being created provides ausagemethod then it will raise anArgumentErrorwith the usage message otherwise it will reraise the originalArgumentError.Here is an example of it in action. Define a
Personclass:and then try and instantiate it without the required arguments:
Note: this isn’t perfect. The main problem being that it is possible that the
ArgumentErrorwe catch has been caused by something other than an incorrect number of arguments being passed toinitializewhich would lead to a misleading message. However it should do what you want in most cases.