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

Metaprogramming का परिचय

Metaprogramming ऐसा code है जो program चलते हुए दूसरे code को लिखता या बदलता है, एक robot की तरह जो अपने लिए नए robot arms बना सकता है। यह Ruby को बहुत flexible बनाता है।

In this page:

  1. Metaprogramming Intro
Syntax
ruby
class ClassName
  define_method(:method_name) { |arg| expression }
end

object.send(:method_name, argument)
object.respond_to?(:method_name)

Metaprogramming Intro

Ruby की metaprogramming code को runtime पर methods और classes define या modify करने देती है, define_method, send, और class_eval जैसे tools इस्तेमाल करते हुए। यही वह है जो कई popular Ruby gems के expressive, लगभग "magic" जैसे APIs को power करता है।

Metaprogramming powerful है लेकिन deliberately इस्तेमाल होना चाहिए -- overuse करना code को straightforward, explicit code से कहीं ज़्यादा पढ़ना और debug करना मुश्किल बना सकता है।

Note: जब आप पहले से method names जानते हों define_method अक्सर method_missing से ज़्यादा safer, ज़्यादा debuggable metaprogramming tool है।

उदाहरण: Metaprogramming Intro

markup
class Product
  %w[name price category].each do |attribute|
    define_method(attribute) do
      instance_variable_get("@#{attribute}")
    end

    define_method("#{attribute}=") do |value|
      instance_variable_set("@#{attribute}", value)
    end
  end
end

p = Product.new
p.name = "Notebook"
p.price = 4.99

puts p.name
puts p.price
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. बिना @ के instance_variable_get("name") इस्तेमाल करना, जो NameError raise करता है।
  2. define_method इस्तेमाल करना और self context की वजह से इसके गलत class पर methods define होने की उम्मीद करना।
  3. metaprogramming लिखना जहाँ एक simple attr_reader काफी हो।
चैप्टर सारांश
  • Idiomatic Ruby, frozen string literals, और symbols बनाम strings चुनना cleaner code की ओर ले जाते हैं।
  • Ruby में सिर्फ nil और false falsy हैं।
  • method_missing और metaprogramming advanced features की तरह introduce हुए।
🔒

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.