Reza
Reza

Reputation: 3038

Ruby: Calling instance method from class method

I want to call some_instance_method from some_class_method. In the following code, the class method is being called from the instance method.

class Foo
  def self.some_class_method
     puts self
  end

  def some_instance_method
    self.class.some_class_method
  end
end

Upvotes: 0

Views: 1248

Answers (3)

boulder
boulder

Reputation: 3266

You need to pass the instance you want to be the recipient of the call to the class method. So the new code is:

class Foo
  def self.some_class_method(instance)
     instance.some_other_instance_method
     puts self
  end

  def some_instance_method
    self.class.some_class_method(self)
  end
end

Notice that the class method is calling 'some_other_instance_method'. If the class method were to call the same method that called it, it would enter an endless loop.

Upvotes: 0

hbejgel
hbejgel

Reputation: 4837

To call an instance method you need to have that object already instantiated somewhere, you can't call an instance method without an object.

def self.some_class_method
  puts self.first.some_instance_method
end

Something like this should work

Upvotes: 0

ptd
ptd

Reputation: 3053

Does what you want to do really make sense? Which instance should the instance method be called on? If it doesn't matter, you can do this:

class Foo
  def self.some_class_method
    new.some_instance_method
    puts self
  end

  def some_instance_method
    self.class.some_class_method
  end
end

This will cause an infinite loop, of course.

Upvotes: 2

Related Questions