Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

10.8. Responding to Calls to Undefined Methods

Problem

Rather than having Ruby raise a NoMethodError when someone calls an undefined method on an instance of your class, you want to intercept the method call and do something else with it.

Or you are faced with having to explicitly define a large (possibly infinite) number of methods for a class. You would rather define a single method that can respond to an infinite number of method names.

Solution

Define a method_missing method for your class. Whenever anyone calls a method that would otherwise result in a NoMethodError, the method_missing method is called instead. It is passed the symbol of the nonexistent method, and any arguments that were passed in.

Here's a class that modifies the default error handling for a missing method:

	class MyClass
	  def defined_method
	    'This method is defined.'
	  end

	  def method_missing(m, *args)
	    "Sorry, I don't know about any #{m} method."
	  end
	end

	o = MyClass.new
	o.defined_method                      # => "This method is defined."
	o.undefined_method
	# => "Sorry, I don't know about any undefined_method method."

In the second example, I'll define an infinitude of new methods on Fixnum by giving it a method_missing implementation. Once I'm done, Fixnum will answer to any method that looks like "plus_#" and takes no arguments.

 class Fixnum def method_missing(m, *args) if args.size > 0 raise ArgumentError.new("wrong number of arguments (#{args.size} for 0)") end match = /^plus_([0-9]+)$/.match(m.to_s) if match self + match.captures[0].to_i ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required