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

Instance Methods का परिचय

एक instance method एक action है जो एक particular object perform कर सकता है, जैसे एक dog जो bark कर सकता है। यह उस object की अपनी details इस्तेमाल कर सकता है।

In this page:

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

markup
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
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. count += 1 में @ भूल जाना, जो NoMethodError raise करता है क्योंकि count एक local variable है।
  2. एक object पर की बजाय class पर एक instance method call करना, जैसे Counter.increment।
  3. यह उम्मीद करना कि increment सिर्फ तभी नई value return करेगा जब last expression assignment हो।
🔒

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.