Instance Methods का परिचय
एक instance method एक action है जो एक particular object perform कर सकता है, जैसे एक dog जो bark कर सकता है। यह उस object की अपनी details इस्तेमाल कर सकता है।
In this page:
Syntax
class ClassName
def method_name(param)
# can use @instance_variables
end
end
object.method_name(argument)
Instance Methods
एक instance method एक class के अंदर def से define होता है और एक specific object की state पर operate करता है, typically इसके instance variables पढ़ते या modify करते हुए।
Class से बना हर object उन instance variables की अपनी independent copy पाता है। Instance methods एक object पर dot notation से call होते हैं, जैसे obj.method_name।
Note:
Instance variables (@var) explicitly assign होने तक automatically nil हैं -- इन्हें पहले से declare करने की ज़रूरत नहीं।
उदाहरण: Instance Methods
class Counter
def initialize
@count = 0
end
def increment
@count += 1
end
def value
@count
end
end
c = Counter.new
c.increment
c.increment
c.increment
puts c.value
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. #}
आम गलतियां
count += 1में@भूल जाना, जोNoMethodErrorraise करता है क्योंकिcountएक local variable है।- एक object पर की बजाय class पर एक instance method call करना, जैसे
Counter.increment। - यह उम्मीद करना कि
incrementसिर्फ तभी नई value return करेगा जब last expression assignment हो।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: