From: lasitha Date: 2009-02-22T15:14:05+09:00 Subject: Re: How to call a module method dynamically On Sun, Feb 22, 2009 at 1:58 AM, 7stud -- wrote: > Can anyone explain why I can do this: > > num = 1 > puts Object.module_eval("num") #=>1 > > def f > "xyz" > end > > puts Object.module_eval("f") #=>xyz > > but I can't do this: > > module Foo > def mymethod > "xyz" > end > end > > puts Foo.module_eval("mymethod") > > --output:-- > `module_eval': undefined local variable or method `mymethod' for > Foo:Module (NameError) > > That result and the result from my previous example seem to imply that > free standing def's are added to Object's singleton class, i.e. they are > class methods. No, they are private instance methods of Object: $: irb 01> def free_standing; end --> nil 02> Object.private_instance_methods.grep /free_standing/ --> [:free_standing] I suppose the confusion comes about because of the line: > puts Object.module_eval("f") #=>xyz The reason this works is not that f was defined as a class method. Its because the context in which f is resolved inherits from Object. 03> Object.module_eval do 04> puts "self: #{self}" 05> puts "ancestors:", self.class.ancestors 06> end self: Object ancestors: Class Module Object PP::ObjectMixin Kernel BasicObject The current object inherits from Object (just like all objects) and the method f was defined as an instance method of Object, so it is available in this context. It is of course confusing that the current object is Object and also inherits from Object. How ruby keeps all that straight is beyond my knowledge :), but it does make sense intuitively. Cheers, lasitha