include और extend
include एक module के actions को एक class से बने objects में mix करता है, जबकि extend इन्हें class में खुद add करता है। यह हर student को skills देने जैसा है या पूरी class को।
In this page:
Syntax
class ClassName
include ModuleName # instance methods
extend ModuleName # class methods
end
include और extend
एक class के अंदर include ModuleName module के methods को instance methods की तरह mix करता है, उस class के objects पर available।
extend ModuleName इसकी बजाय इन्हें class खुद (या एक specific object) पर methods की तरह mix करता है, static/class methods add करने जैसा। इनके बीच चुनना इस पर depend करता है कि behavior individual instances से belong करता है या पूरी class से।
Note:
- include instance methods देता है (objects पर available)।
- extend सीधे class या एक single object पर methods देता है।
उदाहरण: include and extend
module Describable
def describe
puts "This is a #{self.class}"
end
end
module ClassHelpers
def class_info
puts "Class: #{name}"
end
end
class Widget
include Describable
extend ClassHelpers
end
Widget.new.describe
Widget.class_info
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. #}
आम गलतियां
- जब class-level methods चाहिए तब
includeइस्तेमाल करना, इसलिएPerson.class_infoNoMethodErrorraise करता है;extendइस्तेमाल करें। - जब instance methods चाहिए तब
extendइस्तेमाल करना, इसलिए objects को methods नहीं मिलते। - यह भूल जाना कि module को include होने से पहले defined होना ज़रूरी है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: