Home > Back-end >  Defining a method for an instance of a class
Defining a method for an instance of a class

Time:10-21

How do you define a method on an instance of a class and this method is only for the instance and not others?

Please can someone provide a use case for this feature?

CodePudding user response:

Defining a singleton method on an object gives you an object with some new properties. That's it, not more, not less.

Sure, you could achieve the same in another way - create a new class with the desired properties and instantiate it, mix in a module that adds the necessary behavior. And in most practical cases you'd probably do just that.

But think about tests for example where you need to mock some object's method (sure, RSpec framework provides a better way to do this, but still). Or you're debugging the code in REPL and would like to mock some method (for example, to avoid unnecessary side effects). In such cases defining a singleton method is the easiest (fastest) way to get things done.

Just don't think about this "feature" as a separate feature. Because it's not. It is just a consequence of how the Ruby object model works - focus on the latter. I strongly recommend this book for that...

CodePudding user response:

Class methods are called on the class itself which is why in the method declaration, it will always state def self.class_method_name.

Whereas instance methods are called on a particular instance of the class (Not class itself) and they are declared like regular methods i.e def instance_method_name.

For example:

class Car
  def self.class_method
    puts "It's a class method"
  end

  def instance_method
    puts "It's an instance method"
  end
end


Car.class_method => "It's a class method"
Cat.instance_method => undefined method 'instance_method' for Car:Class

Car.new.instance_method => "It's an instance method"
Car.new.class_method => undefined method 'class_method' for Car:Class

For the usecase, here is an example from the Rails:

class Car < ApplicationRecord
  belongs_to :owner
  has_many :passengers

  def self.get_cars(owner) # This is a class method
    Car.includes(:passengers).where(owner: owner).order(created_at: :desc)
  end
end

With Car.get_cars(owner) method, you can get all the cars with your own logic.

  •  Tags:  
  • ruby
  • Related