Metaprogramming का परिचय
Metaprogramming ऐसा code है जो program चलते हुए दूसरे code को लिखता या बदलता है, एक robot की तरह जो अपने लिए नए robot arms बना सकता है। यह Ruby को बहुत flexible बनाता है।
In this page:
Syntax
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
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
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. #}
आम गलतियां
- बिना
@केinstance_variable_get("name")इस्तेमाल करना, जोNameErrorraise करता है। define_methodइस्तेमाल करना औरselfcontext की वजह से इसके गलत class पर methods define होने की उम्मीद करना।- metaprogramming लिखना जहाँ एक simple
attr_readerकाफी हो।
चैप्टर सारांश
- Idiomatic Ruby, frozen string literals, और symbols बनाम strings चुनना cleaner code की ओर ले जाते हैं।
- Ruby में सिर्फ
nilऔरfalsefalsy हैं। method_missingऔर metaprogramming advanced features की तरह introduce हुए।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: