method_missing
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: