From: Rudolf Polzer Date: 2003-03-17T22:22:13+09:00 Subject: Re: dynamically create a method Scripsit ille �Robert Klemme� : > "Rudolf Polzer" schrieb im Newsbeitrag news:slrnb7b7ev.as5.abuse@durchnull.de... > > Scripsit ille �Robert Klemme� : > > > isn't this easier? > > > > > > class Fixnum > > > def power(exp) > > > self ** exp > > > end > > > end > > > > > > a=10 > > > a.power 2 > > > > It is, but there might be cases where one does not know the name of the > > method in advance. > > This wasn't obvious from the original poster's example. But I agree, for > those cases one of the eval approaches has to be used. > > > Perhaps when dynamically creating more than one method > > in method_missing(). > > Hm, I could not imagine a scenario where method_missing is used to > actually create methods. Typically I'd create them before they are > missed. Can you provide an example? With only ONE method, it's easy. For example Perl's autoloader does exactly that. Example in Ruby: autoload.rb: class Autoloaded def method_missing(method, *args) p "Autoloading #{method.to_s()}..." require("Autoloaded/#{method.to_s()}.rb") send(method, *args) end def bar() p "In non-autoloaded method" end end x = Autoloaded.new() x.bar() x.foo() x.foo() x.bar() x.baz() Autoloaded/foo.rb: class Autoloaded def foo() p "In autoloaded method." end end Example: rpolzer@katsuragi ruby $ ruby autoload.rb "In non-autoloaded method" "Autoloading foo..." "In autoloaded method." "In autoloaded method." "In non-autoloaded method" "Autoloading baz..." autoload.rb:4:in `require': No such file to load -- Autoloaded/baz.rb (LoadError) from autoload.rb:4:in `method_missing' from autoload.rb:17 Please do NOT use this simple autoloader. If you want to know why, try creating an empty file "Autoloaded/baz.rb" and see what happens. It's oversimple. Alternatively, do a typo in the class or method name of Autoloaded/foo.rb - you'll get the same bad result. But I did not find an example for dynamically creating a method with dynamically created name... but you can dynamically undefine a method, so you should also be able to define one. And it NEARLY works... except that self seems to be inaccessible. My method completely works, but self has to be accessed with another name and it uses a global array -> ugly. > > And... wasn't there a way to convert a string to a symbol? > > Yes: > > irb(main):006:0> "foo".intern.type "intern" was it... thanks. Why not "to_symbol" or like that? -- Nimm dich in acht vor ihren sch�nen Haaren, Vor ihrem Schmuck, mit dem sie einzig prangt. Wenn sie damit den jungen Mann erlangt, So l��t sie ihn so bald nicht wieder fahren.