2

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)
2
  • When you use object as a parameter, you are calling this method from outside the scope. Use send, or in caller method, do self.fun_pri
    – SwiftMango
    Commented Jun 14, 2012 at 6:44
  • What language is this (ohhh, it was ruby) ? And why do you pass <object> to <caller> function ? <caller> thinks it calls <func_pri> of some other <object> which it can not !
    – Malkocoglu
    Commented Jun 14, 2012 at 6:46

1 Answer 1

5

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'

1
  • Similar to this in java. When you din't specify a receiver for a method, it goes to self instead (ie self is the implicit receiver) Commented Jun 14, 2012 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.