0

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
1
  • What problem are you trying to solve here? You could make your instance method a class method if it has no particular dependency on the instance. Commented Feb 24, 2015 at 23:07

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

The point here is instance methods don't make any sense unless you have an instance to call them on.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.