← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 5 of 6

Namespacing क्या है

Namespacing classes को एक module के अंदर wrap करता है ताकि इनके names clash न हों, दो Sam नाम के लोगों को अलग करने वाले एक family name की तरह। यह बड़े programs को tidy रखता है।

In this page:

  1. Namespacing
Syntax
ruby
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

markup
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
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. module के बाहर Circle.new(3) लिखना, जो NameError raise करता है; Shapes::Circle.new(3) इस्तेमाल करें।
  2. constants के लिए :: की बजाय . इस्तेमाल करना, जैसे Shapes.Circle, जो एक NoMethodError है।
  3. module के अंदर और बाहर दो बार Circle define करना और इन्हें same class होने की उम्मीद करना।
🔒

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.