← Back to Ruby Course | Chapter 9: OOP | Lesson 7 of 7

Modules और Mixins (प्रीव्यू)

एक module helpful actions का एक bundle है जो कई classes share कर सकती हैं, अलग-अलग characters को दिए skill card की तरह। यह preview दिखाता है कि modules classes में कैसे mix होते हैं।
Syntax
ruby
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)

markup
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
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. Greetable.new से एक module का एक object बनाने की कोशिश करना, जो एक NoMethodError है क्योंकि modules instantiated नहीं हो सकते।
  2. include Greetable भूल जाना और फिर greet call करना, जो NoMethodError raise करता है।
  3. name जैसे एक method पर depend करना जिसे including class को define करना ज़रूरी है, इसलिए greet fail होता है जब यह missing हो।
चैप्टर सारांश
  • Classes objects define करती हैं, initialize नए setup करते हुए और instance methods इन्हें behavior देते हुए।
  • attr_accessor getters और setters बनाता है।
  • Inheritance और super behavior reuse करते हैं, और modules और mixins preview किए गए।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.