Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

ruby - What are the differences between "private", "public", and "protected methods"?

I'm learning Ruby, and have come up to a point where I am confused.

The book I am using is talking about private, public, and protected methods, but I am still a bit confused. What are the differences between each?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Public - can be called from anywhere

Private - The method cannot be called outside class scope. The object can only send the message to itself

ex: the baker has bake method as public but break_eggs is private

Protected - You can call an object's protected methods as long as the default object self is an instance of the same class as the object whose method you're calling

ex: with n protected method, c1 can ask c2 to execute c2.n, because c1 and c2 are both instances of the same class

And last but not least:

  • Inheritance: Subclasses inherit the method-access rules of their superclass

if "class D < C", then D will exhibit the same access behaviour as instances of C

reference: http://www.amazon.com/Ruby-Rails-Techniques-Developers/dp/1932394699


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...