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

method_missing क्या है

method_missing एक catch-all है जो तब चलता है जब आप एक method call करते हैं जो exist नहीं करता, एक receptionist की तरह जो तब answer देता है जब कोई और नहीं उठाता। यह एक object को उन names respond करने देता है जो इसने कभी define नहीं कीं।

In this page:

  1. method_missing
Syntax
ruby
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

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
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. #}
आम गलतियां
  1. बिना respond_to_missing? के method_missing override करना, इसलिए respond_to? गलत answer देता है।
  2. दूसरे names के लिए super call करना भूल जाना, typos को silent nil की तरह hide करते हुए बजाय NoMethodError के।
  3. इसे overuse करना, जो debugging मुश्किल बनाता है और method calls धीमी करता है।
🔒

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.