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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Overriding
method_missingwithoutrespond_to_missing?, sorespond_to?gives the wrong answer. - Forgetting to call
superfor other names, hiding typos as silentnilinstead ofNoMethodError. - 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: