Search code examples
rubyoopaccess-specifier

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.


Solution

  • 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