Handling Missing Methods

When Ruby tries to execute an undefined method (or, in object-oriented terms, when an object is sent a message that it cannot handle), the error causes the program to exit. You may prefer your program to recover from such an error. You can do this by writing a method named method_missing, with an argument to which the missing method’s name is assigned. This will execute when a nonexistent method is called:

nomethod1.rb

def method_missing( methodname )
   puts( "Sorry, #{methodname} does not exist" )
end
xxx        #=> Sorry, xxx does not exist

The method_missing method can also take a list of incoming arguments (*args) after the missing method name:

nomethod2.rb

def method_missing( methodname, *args ) puts( "Class #{self.class} does ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.