Modules और Mixins (प्रीव्यू)
एक module helpful actions का एक bundle है जो कई classes share कर सकती हैं, अलग-अलग characters को दिए skill card की तरह। यह preview दिखाता है कि modules classes में कैसे mix होते हैं।
In this page:
Syntax
module ModuleName
def method_name
# body
end
end
class ClassName
include ModuleName
end
Modules और Mixins (Preview)
एक module खुद instantiable हुए बिना related methods और constants साथ group करता है, और unrelated classes के आर-पार behavior share करने के लिए include से एक class में mix हो सकता है -- multiple inheritance का Ruby alternative।
यह यहाँ preview किया गया है और अगले chapter में पूरी detail में cover होगा। Mixins idiomatic Ruby object design की एक defining feature हैं।
Note:
एक class में included एक module effectively खुद को उस class के method lookup chain में insert कर देता है।
उदाहरण: Modules and Mixins (Preview)
module Greetable
def greet
puts "Hello, I'm #{name}"
end
end
class Person
include Greetable
attr_reader :name
def initialize(name)
@name = name
end
end
Person.new("Alice").greet
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. #}
आम गलतियां
Greetable.newसे एक module का एक object बनाने की कोशिश करना, जो एकNoMethodErrorहै क्योंकि modules instantiated नहीं हो सकते।include Greetableभूल जाना और फिरgreetcall करना, जोNoMethodErrorraise करता है।nameजैसे एक method पर depend करना जिसे including class को define करना ज़रूरी है, इसलिएgreetfail होता है जब यह missing हो।
चैप्टर सारांश
- Classes objects define करती हैं,
initializeनए setup करते हुए और instance methods इन्हें behavior देते हुए। attr_accessorgetters और setters बनाता है।- Inheritance और
superbehavior reuse करते हैं, और modules और mixins preview किए गए।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: