Module के Basics
एक module related methods और values के लिए एक named container है, एक label वाले toolbox की तरह। यह ऐसी चीज़ नहीं जिससे आप objects बनाते हैं, बल्कि कुछ ऐसा जो share करना है।
In this page:
Syntax
module ModuleName
CONSTANT = value
def self.method_name
# body
end
end
ModuleName.method_name
Module Basics
एक module module ModuleName ... end से define होता है, related methods, constants, और classes को साथ group करते हुए, एक class जैसा लेकिन .new से instantiated होने की ability के बिना।
Modules दो main purposes serve करते हैं: namespacing (related code organize करना) और mixins (classes के आर-पार behavior share करना)। ये core part हैं कि Ruby multiple class inheritance की ज़रूरत से कैसे बचता है।
Note:
SomeModule.new call करने की कोशिश करना एक NoMethodError raise करता है -- classes के उलट, modules directly instantiated नहीं हो सकते।
उदाहरण: Module Basics
module MathHelpers
def self.square(n)
n * n
end
end
puts MathHelpers.square(6)
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. #}
आम गलतियां
- बिना
self.केdef squaredefine करना औरMathHelpers.squarecall करना, जोNoMethodErrorraise करता है। - lowercase में एक module name करना जैसे module math_helpers, जो एक syntax error है क्योंकि module names constants होने चाहिए जो एक capital letter से शुरू हों।
MathHelpers.newtry करना, जोNoMethodErrorraise करता है क्योंकि एक module instantiated नहीं हो सकता।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: