why can't i access the private function from within the class?

The following code prints NoMethodError. I don't understand the reason . Though the method i am calling is private but i am calling it from within the class.Can't a class var access it's private variable/function ?. I could do this in Java.

class Tester
 private
   def func_pri
     puts("From a private function")
   end

 protected 
  def func_prot
    puts("From a protected function")
  end

 public
  def func_pub
     puts("From a public function")
  end

 public
  def caller(object)
    object.func_pub
    object.func_pri # This statement causes error
    object.func_prot
  end
 end

 o = Tester.new
 o.caller(o)

Answers


You cannot call private methods on an object, not even on self. Remove the object. part, then the call will go on self.

If you do want to call a private method, you can always use object.send(:func_pri).

Ruby is quite different than languages like Java in these terms. For more information, you might want to take a look at http://www.ruby-doc.org/docs/ProgrammingRuby/, chapter 'Classes, Objects, and Variables', section 'Access Control'


Need Your Help

Random Forest discrepancy between R and Matlab & Python

python r matlab machine-learning random-forest

I apply the random forest algorithm in three different programming languages to the same pseudo sample dataset (1000 obs, binary 1/0 dependent variable, 10 numeric explanatory variables):