0

I'm wondering about difference between private and protected in Ruby, there are many sources out there, but they are usually only telling me that private methods cannot be inherited, but in many different ways.

class Person  
  private

  def hello
    puts "hello"
  end
end

class Student < Person

  def initialize
    hello
  end
end

leo = Student.new

But this very simple example proves this claim to be wrong, private method inherited and used. Also if I change 'private' to 'protected' here, its still gonna give me "hello", while creating leo variable. So how is it with public and protected?

Ashish Chopra
  • 1,413
  • 9
  • 23
Leo
  • 2,061
  • 4
  • 30
  • 58

2 Answers2

2

Please, take a look at this blog post Ruby Access Control

From the source:

Public methods can be called by everyone - no access control is enforced. A class's instance methods (these do not belong only to one object; instead, every instance of the class can call them) are public by default; anyone can call them. The initialize method is always private.

Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family. However, usage of protected is limited.

Private methods cannot be called with an explicit receiver - the receiver is always self. This means that private methods can be called only in the context of the current object; you cannot invoke another object's private methods.

Also, I would recommend you read this book The Ruby Programming Language

Andrii Furmanets
  • 1,081
  • 2
  • 12
  • 29
0

First thing I found searching the web:

http://blog.zerosum.org/2007/11/22/ruby-method-visibility

The big difference to other languages seems to be that private methods can be called by subclasses but only without an explicit receiver (even if it is self). Receiver here is meant in the Smalltalk OO kind of way that invoking a method on an object can be seen as sending a message to the object. When you write just "hello" in your example it is without an explicit receiver and the implicit receiver is self, so it works, although it contradicts the semantics of some other OO languages.

skno
  • 1