How Is Visibility Of Methods Changed In Ruby (encapsulation)?
How Is Visibility Of Methods Changed In Ruby (encapsulation)?
In Ruby, you can control the visibility of methods using the keywords public
, private
, and protected
. This allows you to achieve encapsulation by hiding implementation details and controlling access to the methods of a class[1].
Public methods are the default visibility in Ruby. They can be called from anywhere, both inside and outside the class[1].
Private methods can only be called from within the class they are defined in, or from subclasses. They are implicitly invoked on self
and cannot be called with an explicit receiver[1][2].
To define a private method, use the private
keyword followed by the method definitions:
class MyClass
def public_method
# ...
end
private
def private_method
# ...
end
end
Protected methods are similar to private methods, but they can be call...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào