Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access private methods

Tags:

ruby

My understanding is that private means being private to an instance. Private methods can't be called with an explicit receiver, even self. To call a private method, I have to go through a process like below:

class Sample   def foo     baz   end    private   def baz    end  end   Sample.new.foo 

This will call the private baz method. Is there a way to directly call a private method with an explicit receiver?

like image 582
mhaseeb Avatar asked Dec 20 '15 09:12

mhaseeb


People also ask

How can I access a private method from another class?

Accessing Private Constructors of a class To access the private constructor, we use the method getDeclaredConstructor(). The getDeclaredConstructor() is used to access a parameterless as well as a parametrized constructor of a class.

How do you access private member functions?

How to access the Private Member Function in C++? A function declared inside the private access specifier of the class, is known as a private member function. A private member function can be accessed through the only public member function of the same class. rNo is used to store the roll number of the student.

Can we call private method from outside class Java?

We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.


2 Answers

Yes, this is possible with Kernel#send:

receiver.send :method_name, parameters 

Though there are workarounds like BasicObject#instance_eval, or Kernel#binding manipulations, the common way to call private method is to call send on the receiver.

like image 175
Aleksei Matiushkin Avatar answered Sep 20 '22 19:09

Aleksei Matiushkin


Using BasicObject#instance_eval, you can call private method.

class Sample   private   def baz     'baz called'   end end  Sample.new.instance_eval('baz') # => 'baz called' Sample.new.instance_eval { baz } # => 'baz called' 
like image 44
falsetru Avatar answered Sep 21 '22 19:09

falsetru