Main Content

Private, Protected, Public in Ruby. What about interfaces and abstract classes in Ruby?

Archive - Originally posted on "The Horse's Mouth" - 2012-06-23 12:18:45 - Graham Ellis

There's no requirement for you to use the words "public", "private" and "protected" in Ruby - methods within classes that you write default to being public anyway. But you may wish to protect certain of your methods from being called directly by the users of your classes.

So - what protection do they give?

If you give a private command, then it means that the following method(s) up to the next protected or public command are only callable without an explicit object reference.. So this means that you must be within the class when you call them, and furthermore you must call them on the current object. adding self. in front of a call wouldn't change the meaning, but it would lead to NoMethodError exception.

If you give a protected command, then it means that the following method(s) up to the next private or public command are only accessible when called from within methods in the current class, or from methods within classes which are derived (extended) from that class.

Example - see [here] from last week's Ruby course.

As well as the use of "private" (especially) being rather different in Ruby to other languages, you'll note that Ruby has no concept of an abstract class - it doesn't need one, though there are some online examples if you want to write a class that forces actions on anyone extending it.

You'll also note that Ruby does not offer multiple inheritance, nor interfaces. But it does offer mixins which allow you to pull in additional common code into multiple classes in addition to inheritance. See [here] for an article on that topic, and examples.