Getting methods defined in the top scope

T

Thilina Buddhika

I am trying to get the names of the methods defined by myself in the top
scope. I tried it by using
" self.class.private_instance_methods(false).sort "

But it gives two additional methods given below.
inherited
initialize


but i want to get only the methods defined by my self. Is there any way
to solve this ?

thanks!

regards,
buddhika
 
7

7stud --

Thilina said:
I am trying to get the names of the methods defined by myself in the top
scope. I tried it by using
" self.class.private_instance_methods(false).sort "

But it gives two additional methods given below.
inherited
initialize


but i want to get only the methods defined by my self. Is there any way
to solve this ?

thanks!

regards,
buddhika



def hello
end

def goodbye
end

class Dog
end

value = 10

#---------


p Object.private_instance_methods(false)
--->["goodbye", "initialize", "hello"] #No inherited method anywhere.


method_names = Object.private_instance_methods(false)
my_methods = []

method_names.each do |meth_name|
if meth_name == 'initialize' or meth_name == 'inherited'
next
end

my_methods << meth_name
end

p my_methods
-->["goodbye", "hello"]
 
R

Raul Parolari

Thilina said:
I am trying to get the names of the methods defined by myself in the top
scope. I tried it by using
" self.class.private_instance_methods(false).sort "

But it gives two additional methods given below.
inherited
initialize

but i want to get only the methods defined by my self. Is there any way
to solve this ?

thanks!

regards,
buddhika

In the same line of thought as previous response, but more concise:

not_mine = %w[initialize .. ]

my_methods = Object.private_instance_methods(false) - not_mine
 
G

George

but i want to get only the methods defined by my self. Is there any way
to solve this ?

This gives the same result as the others, but avoids hardcoding method names:

$ cat toplevel_methods.rb
TOPLEVEL_METHODS = []

def Object.method_added(name)
TOPLEVEL_METHODS << name if private_method_defined?(name)
end

def toplevel
end

class Object
def not_toplevel
end

private
def fake_toplevel
end
end

p TOPLEVEL_METHODS

$ ruby toplevel_methods.rb
[:toplevel, :fake_toplevel]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top