Reputation: 2183
I am just curious to know that what is exactly difference between methods
and public_methods
in Ruby?
From RubyMonk Analysis section
The methods method on Object allows us to tap into to the list of public methods available on an Object and its ancestors. This is equivalent to using public_methods. They return all the instance methods and the class methods belonging to that object and the ones accessible on that object's ancestors. If you want to ignore the ancestors and restrict the listing to just the receiver, you can pass in false to public_methods(false).
For curiosity, i also call methods(false)
that return different output from
public_methods(false)
My sample code and output:
p String.methods.size
p String.public_methods.size
p String.methods(false).size
p String.public_methods(false).size
p String.public_methods(false) - String.methods(false)
STDOUT:
235
235
3
19
[:json_create, :yaml_tag, :const_missing, :allocate, :new, :superclass, :cattr_reader, :cattr_writer, :cattr_accessor, :class_attribute, :superclass_delegating_accessor, :descendants, :subclasses, :duplicable?, :json_creatable?, :to_yaml]
From above output i just see that methods
and public_methods
are not same but can't find out what is exactly difference between them.
Upvotes: 5
Views: 892
Reputation: 19221
In the Object class documentation for Object#public_methods
:
Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
In contrast, the documentation for Object#methods
state:
Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj’s ancestors. If the optional parameter is false, it returns an array of obj‘s public and protected singleton methods, the array will not include methods in modules included in obj.
So:
#public_methods
returns only the methods which are public, whereas #methods
returns also (names of) protected methods.
The false
parameter has different effects. I'm not too sure about the scope of the difference, but it seems to me that the main difference would be singleton methods vs. instance methods*.
*'instance methods' can also refer to class methods if class is the receiver - as everything is an object and, as stated in the Class documentation:
Classes in Ruby are first-class objects---each is an instance of class Class.
Upvotes: 6