This was the tip of the week in the July 15, 2021 Ruby Weekly Newsletter.


Often when learning about an object, it can be useful to see the methods available to call on the object. I find this helpful when debugging, using a new gem, or simply looking to learn more about an object.

Luckily, Ruby exposes Object#public_methods, Object#protected_methods and Object#private_methods, all of which return a list of symbols representing the names of methods defined on an object. For example, if we wanted to see the public methods defined on true, we could do:

true.public_methods
=> [:===, :^, :inspect, :to_s, :&, :|,
:taint, :tainted?, :untaint, :untrust,
:untrusted?, :trust, :methods,
:singleton_methods, :protected_methods,
:private_methods, :public_methods...

  ... many many more! ...

..., :instance_exec, :__send__]

There are 61 many public methods, quite a lot! This isn’t because there are many methods defined explicitly on TrueClass itself, but rather because of all the methods defined on ancestors of TrueClass.

true.class.ancestors
=> [TrueClass, Object, Kernel, BasicObject]

This brings us to the crux of this week’s tip. Object#public_methods, Object#protected_methods and Object#private_methods all take an optional boolean parameter denoting whether to include methods defined on ancestors. This means if we pass in false to Object#public_methods, we should see only the methods in the receiver.

true.public_methods(false)
=> [:===, :^, :inspect, :to_s, :&, :|]

This is a much more comprehensible list, and more helpful when looking to learn about the nuances of a specific object.