Ruby Interview Questions
Can you tell me the three levels of method access control for classes and modules? What do they imply about the method?
All methods, no matter the access control, can be accessed within the class. But what about outside callers? Public methods enforce no access control -- they can be called in any scope. Protected methods are only accessible to other objects of the same class. Private methods are only accessible within the context of the current object.
class AccessLevel def something_interesting another = AccessLevel.new another.public_method another.protected_method another.private_method end def public_method puts "Public method. Nice to meet you." end protected def protected_method puts "Protected method. Sweet!" end private def private_method puts "Incoming exception!" end end AccessLevel.new.something_interesting #=> Public method. Nice to meet you. #=> Protected method. Sweet! #=> NoMethodError: private method ‘private_method’ called for #=> #