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

method_missing

In this page:

  1. method_missing

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
🔒

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.