How is the invocation of a private method different than the invocation of a public method from within its
defining class?
How is the invocation of a private method different than the invocation of a public method from within its
defining class?
In Ruby, the invocation of private and public methods within their defining class is governed by the language's access control rules.
Public methods are part of the class's interface and can be called by any other object or class. Within the defining class, a public method is invoked just like any other method, using either an explicit receiver like self.method_name
or an implicit receiver by simply calling method_name
.
Private methods, however, have a restricted scope. They are only accessible within the context of the defining class and cannot be called with an explicit receiver, not even with self
. This means that private methods must be invoked without a receiver, or in other words, you must use a "functional style" for calling them.
Here's an example to illustrate the difference:
class Example
def public_method
puts "I'm a public method!"
end
private
def private_method
puts "I'm a private method!"
end
def use_methods
public_method # This is valid.
self.public_method # This is also valid.
private_method # This is valid.
self.private_method # This would raise a NoMethodError because private methods cannot be called with an explicit receiver.
end
end
In the example above, public_method
can be called with or without the self
receiver from within the class. However, private_method
can only be called without an explicit receiver.
Ruby's private access control is unique compared to some other object-oriented languages in that private methods can be called by any in...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào