← Back to Ruby Course | Chapter 12: Ruby Best Practices | Lesson 5 of 6

method_missing

method_missing is a catch-all that runs when you call a method that does not exist, like a receptionist who answers when nobody else picks up. It lets an object respond to names it never defined.

In this page:

  1. method_missing
Syntax
ruby
class ClassName
  def method_missing(name, *args, &block)
    # handle unknown method calls
    super
  end

  def respond_to_missing?(name, include_private = false)
    super
  end
end

method_missing

method_missing is a special method you can override on a class to intercept calls to methods that don't actually exist, letting you handle them dynamically instead of raising a NoMethodError.

It's a powerful metaprogramming tool used by libraries to build flexible, dynamic APIs. It should be used carefully, since it can make code harder to understand and debug if overused.

Warning: Overriding method_missing without also overriding respond_to_missing? can make objects behave inconsistently with introspection tools like respond_to?.

Example: method_missing

markup
class DynamicGreeter
  def method_missing(name, *args)
    if name.to_s.start_with?("greet_")
      language = name.to_s.sub("greet_", "")
      puts "Hello in #{language}!"
    else
      super
    end
  end
end

greeter = DynamicGreeter.new
greeter.greet_spanish
greeter.greet_french
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Overriding method_missing without respond_to_missing?, so respond_to? gives the wrong answer.
  2. Forgetting to call super for other names, hiding typos as silent nil instead of NoMethodError.
  3. Overusing it, which makes debugging harder and slows method calls.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.