✅ Instance Methods

  • Are called on instances (objects) of a class.
  • Use a single def keyword, like def method_name.
  • Operate on data stored in the object (i.e., instance variables like @name).
class Dog
  def initialize(name)
    @name = name
  end

  def speak
    "Woof! My name is #{@name}"
  end
end

dog = Dog.new("Fido")
puts dog.speak  # => "Woof! My name is Fido"

✅ Class Methods

  • Are called on the class itself, not instances.
  • Use self. prefix in the method name, like def self.method_name.
  • Often used for utility methods or constructors.
class Dog
  def self.species
    "Canis familiaris"
  end
end

puts Dog.species  # => "Canis familiaris"

Here’s an example showing both instance and class methods in a single Ruby class:

class Dog
  @@count = 0  # class variable to track number of dogs

  def initialize(name)
    @name = name  # instance variable
    @@count += 1
  end

  # Instance method
  def speak
    "Woof! My name is #{@name}"
  end

  # Class method
  def self.total_dogs
    "There are #{@@count} dogs."
  end
end

# Creating instances
dog1 = Dog.new("Buddy")
dog2 = Dog.new("Max")

# Calling instance methods
puts dog1.speak    # => "Woof! My name is Buddy"
puts dog2.speak    # => "Woof! My name is Max"

# Calling class method
puts Dog.total_dogs  # => "There are 2 dogs."
  • Dog.new("Buddy") creates an instance and runs the initialize method.
  • @name is an instance variable: each dog has its own.
  • @@count is a class variable: shared across all dogs.
  • speak is an instance method.
  • self.total_dogs is a class method, giving information about the class as a whole.