ruby - Where do methods defined at the top-level exist? -


i learning metaprogramming , stuck trying find method. let's have following class:

class myclass   def self.my_method   end   def your_method   end end 

with following code can search each method in object space:

type = class name = /^my_method$/ result = objectspace.each_object(type).select |o|   o.instance_methods(false).grep(name).size > 0 || o.methods.grep(name).size > 0 end p result 

and finds showing following output:

[myclass] 

as searcher code searches instance methods, shows same output when looking your_method.

even if add singleton method object:

mc = myclass.new def mc.our_method end 

just changing searcher this:

type = object name = /^our_method$/ result = objectspace.each_object(type).select |o|   o.methods.grep(name).size > 0 end p result 

it finds it:

[#<myclass:0x8f86760>] 

the question is, how find method defined in top level object? method:

def hidden end 

besides, current class when defining method this?

which current class when defining method this?

we can figure out object we’re in inspecting self in top level scope:

self        #=> main self.class  #=> object 

so we’re not in class, instance of object dubbed “main”.


how find method defined in top level object?

this gets interesting. top-level scope object in ruby behaves specially, it’s relatively easy discover method here defined lives:

def foo; :bar; end method(:foo).owner     #=> object object.new.foo         #=> nomethoderror: private method `foo' called object.new.send(:foo)  #=> :bar 

so methods defined @ top-level made (private*) instance methods of object. reason ”searcher” cannot find because these methods private, , neither methods nor instance_methods include private methods, instead need private_methods , private_instance_methods:

object.instance_methods.include?(:foo)          #=> false object.private_instance_methods.include?(:foo)  #=> true 

* note pry (at least v0.10.1) alters make methods defined @ top-level in repl public.


Comments

Popular posts from this blog

c++ - OpenMP unpredictable overhead -

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

javascript - Wordpress slider, not displayed 100% width -