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

Instance Methods

An instance method is an action a particular object can perform, like a dog that can bark. It can use that object's own 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

An instance method is defined inside a class with def and operates on a specific object's state, typically reading or modifying its instance variables.

Every object created from the class gets its own independent copy of those instance variables. Instance methods are called on an object with dot notation, like obj.method_name.

Note: Instance variables (@var) are automatically nil until explicitly assigned -- there's no need to declare them ahead of time.

Example: 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. #}
Common Mistakes
  1. Forgetting @ in count += 1, which raises NoMethodError because count is a local variable.
  2. Calling an instance method on the class, as in Counter.increment, instead of on an object.
  3. Expecting increment to return the new value only when the last expression is the 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.