Namespacing क्या है
Namespacing classes को एक module के अंदर wrap करता है ताकि इनके names clash न हों, दो Sam नाम के लोगों को अलग करने वाले एक family name की तरह। यह बड़े programs को tidy रखता है।
In this page:
Syntax
module Namespace
class ClassName
# body
end
end
Namespace::ClassName.new
Namespacing
एक module related code group करने और name collisions avoid करने के लिए classes wrap कर सकता है, :: से accessed, जैसे Shapes::Circle।
यह खासकर बड़े codebases या libraries में useful है जहाँ दो unrelated classes otherwise same short name चाहती हों। एक module से Namespacing purely organizational है और इसका कोई अपना behavior नहीं जोड़ता।
Note:
एक namespacing module तक पहुँचने के लिए
:: इस्तेमाल करें, जैसे Shapes::Circle.new, . से अलग जो एक method call करता है।उदाहरण: Namespacing
module Shapes
class Circle
def initialize(radius)
@radius = radius
end
def area
3.14159 * @radius ** 2
end
end
end
circle = Shapes::Circle.new(3)
puts circle.area
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. #}
आम गलतियां
- module के बाहर
Circle.new(3)लिखना, जोNameErrorraise करता है;Shapes::Circle.new(3)इस्तेमाल करें। - constants के लिए
::की बजाय.इस्तेमाल करना, जैसेShapes.Circle, जो एकNoMethodErrorहै। - module के अंदर और बाहर दो बार
Circledefine करना और इन्हें same class होने की उम्मीद करना।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: