method_missing (Ruby)
method_missing is a hook Ruby calls when an object receives a message it has no method for. Overriding it lets you handle arbitrary, undefined method calls dynamically — a key metaprogramming tool.
Ruby
When you call a method that doesn't exist, Ruby invokes method_missing(name, *args, &block) before raising NoMethodError. By defining your own method_missing, you can intercept those calls and respond programmatically — the technique behind dynamic finders, proxies, and flexible DSLs.
Good practice is to handle only the patterns you recognize and call super for everything else (so genuine typos still raise errors), and to also override respond_to_missing? so that respond_to? and introspection stay honest about which 'methods' your object accepts.
method_missing is powerful but has costs: it's slower than real methods, can hide typos, and complicates debugging. For frequently used dynamic methods, prefer define_method to generate real methods instead.
Syntax
def method_missing(name, *args)
# handle or super
endExamples
Ruby
class Ghost
def method_missing(name, *args)
"you called #{name} with #{args.inspect}"
end
end
puts Ghost.new.anything(1, 2)Output:
you called anything with [1, 2]