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

Module के Basics

एक module related methods और values के लिए एक named container है, एक label वाले toolbox की तरह। यह ऐसी चीज़ नहीं जिससे आप objects बनाते हैं, बल्कि कुछ ऐसा जो share करना है।

In this page:

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

markup
module MathHelpers
  def self.square(n)
    n * n
  end
end

puts MathHelpers.square(6)
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. बिना self. के def square define करना और MathHelpers.square call करना, जो NoMethodError raise करता है।
  2. lowercase में एक module name करना जैसे module math_helpers, जो एक syntax error है क्योंकि module names constants होने चाहिए जो एक capital letter से शुरू हों।
  3. MathHelpers.new try करना, जो NoMethodError raise करता है क्योंकि एक module instantiated नहीं हो सकता।
🔒

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.