Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 134 ยท Methods and Blocks

method_missing and respond_to_missing?

Learn how Ruby's method_missing builds ghost methods, why respond_to_missing? must come with it, how to avoid infinite recursion, and when define_method is better.

When you call object.something, Ruby looks for a method named something in the object's class and its ancestors. If it finds none, Ruby does not give up immediately. It calls a special method named method_missing on the object, passing the name and the arguments. The default implementation raises the familiar NoMethodError, but you can override it to decide what happens instead. Methods that answer calls without ever being defined are called ghost methods, and they power some of Ruby's most famous libraries: dynamic finders (find_by_name), proxies, builders and OpenStruct.

This is a powerful tool and an easy one to misuse. You will learn how the lookup fails, how to write a correct method_missing, why respond_to_missing? is its inseparable partner, and the safer alternative of defining real methods on demand.

What happens on a failed call

Ruby NoMethodError and what it says (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints walking; the second ends with main.rb:7:in '<main>': undefined method 'fly' for an instance of Robot (NoMethodError). Behind the scenes Ruby called r.method_missing(:fly), and the inherited implementation in BasicObject raised that error. All we need to do is define our own.

A first ghost method

method_missing(name, *args, &block) receives the called name as a symbol, any positional arguments and the block. Whatever it returns becomes the result of the call.

Ruby A method_missing that answers anything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Every unknown name works, which is exactly the problem: this object accepts typos silently and respond_to? lies, returning false although the object answers. A good method_missing accepts only the names it understands and passes everything else to super.

The correct pattern

A well-behaved implementation has three parts:

  1. check whether the name is one it handles;
  2. otherwise call super, so that NoMethodError is still raised for real mistakes;
  3. add respond_to_missing? so that respond_to? and method agree.
Ruby A settings object with dynamic readers and writers (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The final call fails with undefined method 'colour' for an instance of Settings (NoMethodError) raised by super, exactly like a normal missing method, and that is the behavior you want. Look at the structure: reader, writer and predicate are handled by cases, and everything else goes to super.

respond_to_missing? is the same decision in question form. Ruby calls it from respond_to?, and from method, so s.method(:theme) works (the Method object forwards to method_missing). Without it, code that checks respond_to? first (such as Array#flatten, puts or JSON generation) behaves wrongly with your object. Always define both or neither.

Make respond_to_missing? and method_missing use the same rule. A small private helper such as handles?(name) that both methods call prevents them from drifting apart.

Why super matters: swallowing mistakes

If you forget the super branch, every typo turns into a silent nil. The bug appears far away from the typo, which makes it hard to track down.

Ruby The silent catch-all trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

config.prot returns nil with no warning. Worse, Ruby itself calls methods such as to_ary, to_str and to_hash on objects during flatten, puts and keyword splatting. Here to_ary returned nil, which Ruby accepts as "no conversion", but a catch-all that returns anything else (like a string) can make Ruby do strange things. Your object should say "no" to names it does not own.

Infinite recursion

Inside method_missing, any call to another undefined method triggers method_missing again. The classic accident is a typo or an uninitialised instance variable accessor:

Ruby method_missing calling itself (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The rescue block prints SystemStackError and stack level too deep. The final call is left unrescued, so the program ends with main.rb:3:in 'Broken#method_missing': stack level too deep (SystemStackError) followed by a long backtrace of the same line (the runner shows about ten thousand levels). Every missing helper re-enters method_missing, so nothing ever returns. Calling super for unknown names, as in the correct pattern, breaks the cycle because the base implementation raises instead of looping.

Proxies and delegation

A classic legitimate use is a proxy that forwards calls to another object while adding behavior such as logging, caching or access control. The proxy only needs to know "forward everything".

Ruby A logging proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inheriting from BasicObject is the trick: it has almost no methods (not even inspect, class or puts), so nearly every call reaches method_missing. A proxy based on Object would answer to_s, ==, class and dozens more on its own and forward none of them. The cost is that BasicObject has no Kernel, so inside the class you must write ::Kernel, ::Array and so on with the leading ::. Real programs often use the standard library's SimpleDelegator instead (Forwardable and Delegation).

Passing arguments through: *args, **kwargs, &block

To forward faithfully, accept everything and pass it on. Since Ruby 3.0 keyword arguments are separate from positional ones, so forwarding with *args alone can lose them. Use ..., or name all three parts.

Ruby Forwarding positional, keyword and block arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

method_missing(name, ...) captures everything after the name, including keywords and the block, and public_send(name, ...) hands it all on unchanged. It is the shortest correct forwarder. Use public_send rather than send so that private methods stay private.

Define on first use: the faster alternative

Each ghost-method call pays for a full failed lookup first, then method_missing. That is slow for hot paths. A common optimisation is to define a real method the first time a name is requested and from then on let normal lookup find it:

Ruby method_missing that defines the method it just handled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The "(defining name)" line appears once per name. The second r.name is an ordinary, fast call. When the set of names is known in advance, as with FIELDS here, skip method_missing completely and define the methods in a loop with define_method: the methods then appear in methods and instance_methods, and tools such as debuggers and documentation generators can see them. Reserve method_missing for names you cannot enumerate ahead of time.

Class-level method_missing and const_missing

method_missing also works at the class level, by defining it on the singleton: def self.method_missing(...). Rails' find_by_email style finders are built like this.

Ruby Dynamic finders on a class (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The parsing of the method name with a regular expression is the typical shape of a ghost method: the name carries data. Anything that does not match goes to super, so User.delete_everything raises undefined method 'delete_everything' for class User (NoMethodError).

When to use it, when to avoid it

Good reasons

  • Proxies, decorators and wrappers that forward unknown calls.
  • Objects whose interface comes from data you only learn at runtime (remote APIs, configuration files, OpenStruct-like containers).
  • Builders and DSLs where method names are the content, such as an HTML builder where div and span are not predefined.

Better alternatives

  • A known list of names: define_method in a loop.
  • A few similar methods: write them out, or use Struct / Data.
  • A catch-all lookup: a plain Hash and fetch, which gives a clear KeyError.

Rules to follow every time

  • Handle only specific names; send the rest to super.
  • Define respond_to_missing? with the same rule.
  • Never call undefined methods from inside it; guard against recursion.
  • Keep it fast or define real methods on first use.
  • Document ghost methods, since they do not appear in methods.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does Ruby call method_missing?

    Ruby calls method_missing as the last step of a failed lookup. The default implementation raises NoMethodError.
  2. 2. Why should method_missing call super for names it does not handle?

    Without super, every unknown name is answered (often with nil), which hides bugs and confuses code that probes objects with to_ary or to_str.
  3. 3. What is respond_to_missing? for?

    respond_to? only knows real methods unless you override respond_to_missing?. Defining it keeps your object's interface honest.
  4. 4. What is the main performance drawback of ghost methods, and the usual fix?

    A failed method lookup plus a method_missing call is slower than a normal call. Defining the method the first time makes later calls normal and fast.
  5. 5. Why does a logging proxy often inherit from BasicObject?

    An Object-based proxy would answer to_s, class, == and many others itself instead of forwarding them.

Summary

  • A failed method lookup calls method_missing(name, *args, &block); the default raises NoMethodError.
  • Handle only the names you understand and send everything else to super.
  • Pair it with respond_to_missing? so respond_to? and method tell the truth.
  • Avoid infinite recursion: never call undefined methods inside method_missing.
  • Forward with (name, ...) and public_send; base proxies on BasicObject.
  • Ghost methods are slow and invisible to tools: prefer define_method for known names, or define the method on first use.

Next: Refinements