What is actually occurring when private
/protected
is stated within a Ruby class definition? They are not keywords, so that implies they must be method calls, but I cannot find where they are defined. They do not appear to be documented. Are the two different ways of declaring private
/protected
methods (shown below) implemented differently? (The second way is obviously a method call, but this is not so apparent in the first way.)
class Foo
private
def i_am_private; end
def so_am_i; end
end
class Foo
def i_am_private; end
def so_am_i; end
private :i_am_private, :so_am_i
end
protected methods can be called by any instance of the defining class or its subclasses. private methods can be called only from within the calling object. You cannot access another instance's private methods directly.
What is a private method in Ruby? It's a type of method that you can ONLY call from inside the class where it's defined. This allows you to control access to your methods.
In Ruby, a protected method (or protected message handler) can only respond to a message with an implicit/explicit receiver (object) of the same family. It also cannot respond to a message sent from outside of the protected message handler context.
Protected methods can only be called by objects of the defined class and its subclass. The access of these methods is limited in between the defined class or its subclass. You cannot access protected methods outside the defined class or its subclass. The usage of protected methods is finite.
Both are method calls. Quoting from docs:
Each function can be used in two different ways.
- If used with no arguments, the three functions set the default access control of subsequently defined methods.
- With arguments, the functions set the access control of the named methods and constants.
See documentation here:
You were looking for how the Module.private
method comes into existence. Here is where that happens. And here is some more information about it. You would have to read more into it, starting from rb_define_private_method
defined in class.c
.
Hope that helps!
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