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

Instance Methods

In this page:

  1. Instance Methods

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
🔒

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.