method_missing क्या है
method_missing एक catch-all है जो तब चलता है जब आप एक method call करते हैं जो exist नहीं करता, एक receptionist की तरह जो तब answer देता है जब कोई और नहीं उठाता। यह एक object को उन names respond करने देता है जो इसने कभी define नहीं कीं।
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 एक special method है जिसे आप एक class पर override कर सकते हैं उन methods की calls intercept करने के लिए जो actually exist नहीं करतीं, आपको एक NoMethodError raise करने की बजाय इन्हें dynamically handle करने देते हुए।
यह एक powerful metaprogramming tool है जो libraries flexible, dynamic APIs बनाने के लिए इस्तेमाल करती हैं। इसे carefully इस्तेमाल करना चाहिए, क्योंकि overuse होने पर यह code को समझना और debug करना मुश्किल बना सकता है।
Warning:
respond_to_missing? को भी override किए बिना method_missing override करना objects को respond_to? जैसे introspection tools के साथ inconsistently behave करवा सकता है।
उदाहरण: 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. #}
आम गलतियां
- बिना
respond_to_missing?केmethod_missingoverride करना, इसलिएrespond_to?गलत answer देता है। - दूसरे names के लिए
supercall करना भूल जाना, typos को silentnilकी तरह hide करते हुए बजायNoMethodErrorके। - इसे overuse करना, जो debugging मुश्किल बनाता है और method calls धीमी करता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: