4

In Ruby, you can do ...

Object.send(:public, *Object.private_instance_methods)

... as seen in this answer to another question. This redefines each of the private instance methods of Object, making them public. My question is: how does this work? send is supposed to work with the name of a method, but there do not seem to be methods named public, private, or protected defined on Object (or at least my search-fu has not found them).

> Object.respond_to?(:public)
=> false 
Community
  • 1
  • 1
Pathogen
  • 845
  • 11
  • 16

1 Answers1

4

There is indeed a method called public, but it is defined on Module. This is ok because Object is an instance of Class and the superclass of Class is Module: apart from the slight circularity in the ruby class hierarchy bootstrapping this is just normal ruby inheritance.

Your respond_to? check returns false because by default respond_to? does not check protected or private methods (prior to ruby 2.0 it checked protected methods). You can request that all methods be searched by doing

Object.respond_to?(:public, true)

which does return true.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • Interesting! Also, after tinkering around further, I see that making the private methods of Object public does not make the mixed in methods from Module public. – Pathogen Oct 27 '15 at 20:29