Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a private instance method from a class method in Ruby

Can I create a private instance method that can be called by a class method?

class Foo
  def initialize(n)
    @n = n
  end
  private # or protected?
  def plus(n)
    @n += n
  end
end

class Foo
  def Foo.bar(my_instance, n)
    my_instance.plus(n)
  end
end

a = Foo.new(5)
a.plus(3) # This should not be allowed, but
Foo.bar(a, 3) # I want to allow this

Apologies if this is a pretty elementary question, but I haven't been able to Google my way to a solution.

like image 756
user4812 Avatar asked Jan 07 '09 15:01

user4812


People also ask

Can a class method call a private method?

Overview. The private method of a class can only be accessible inside the class. The private methods cannot be called using the object outside of the class. If we try to access the private method outside the class, we'll get SyntaxError .

Can you call an instance method in a class method Ruby?

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.

How can we call private methods in Ruby?

Understanding Private Methods in Ruby You can only use a private method by itself. It's the same method, but you have to call it like this. Private methods are always called within the context of self .

Can you call a private method outside a Ruby class using its object?

Using the private method with explicit arguments. Using the private method (“wrapper” syntax) Private methods can't be called outside the class. Private methods can be called inside a class inside other methods.


1 Answers

Using private or protected really don't do that much in Ruby. You can call send on any object and use any method it has.

class Foo
  def Foo.bar(my_instance, n)
    my_instance.send(:plus, n)
  end
end
like image 135
Samuel Avatar answered Sep 22 '22 12:09

Samuel