[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Getting methods defined in the top scope

Thilina Buddhika

11/12/2007 5:53:00 AM


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
--
Posted via http://www.ruby-....

4 Answers

7stud --

11/12/2007 6:27:00 AM

0

Thilina Buddhika wrote:
>
> 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"]
--
Posted via http://www.ruby-....

Raul Raul

11/12/2007 6:48:00 AM

0

Thilina Buddhika wrote:
>
> 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
--
Posted via http://www.ruby-....

George

11/12/2007 7:34:00 AM

0

On Nov 12, 2007 4:53 PM, Thilina Buddhika <thilinamb@gmail.com> wrote:
>
> 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]

Thilina Buddhika

11/12/2007 7:45:00 AM

0


thanks guys!

Regards,
buddhika
--
Posted via http://www.ruby-....