Reputation: 2077
In Ruby we have simple ways to get all the local variables, global variables with local_variables
and global_variables
method.
We can list the constants with Object.constants
But is there a builtin way to list all the Object methods?
Something like this:
def foo() end
def bar() end
def baz() end
# As `Array.new.methods' or `Array.instance_methods` returns all the methods of an Array object...
# Code to return all the methods defined above # => [:foo, :bar, :baz]
In IRB, I can write:
def foo() end
p [self.methods.include?(:foo), self.respond_to?(:foo)]
And the output is [true, true]
in IRB, but in a file, the output to standard output is [false, false]
Similarly if I run the following code:
def foo() end
puts Object.new.methods.include?(:foo)
In IRB, I get true
, and if it's saved in a file, I get false
Here's a link which didn't help much:
How to list all methods for an object in Ruby?
Just because it talks about getting methods of a class or a module. But I want to list the methods defined in the top self object.
Upvotes: 2
Views: 1071
Reputation: 54313
The closest I could find is to call private_methods
on the main
object, with false
as argument
Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.
def foo
"foo"
end
def bar
"bar"
end
def baz
"baz"
end
p private_methods(false)
# [:include, :using, :public, :private, :define_method, :DelegateClass, :foo, :bar, :baz]
If you omit the argument, you also get all the private methods defined in Kernel
or BasicObject
.
In order to refine the list further, you could select the methods defined for Object
:
p private_methods(false).select{|m| method(m).owner == Object}
#=> [:DelegateClass, :foo, :bar, :baz]
Only :DelegateClass
is left, because it is defined in the top-level scope, just like :foo
, :bar
and :baz
.
Upvotes: 3
Reputation: 106147
You're getting false
because methods defined in the top level context are private by default.
def foo; end
p self.private_methods.include?(:foo)
# => true
I'm not sure if this is documented anywhere.
In order to get all methods, including private ones, you'll need to do e.g.:
all_methods = self.methods | self.private_methods
Try it on repl.it: https://repl.it/@jrunning/DutifulPolishedCell
Upvotes: 1