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.
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 .
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With