From: Paul Lutus Date: 2006-12-12T06:25:05+09:00 Subject: Re: best way to dynamically create new instance methods Dan Tenenbaum wrote: > That seems pretty simple but I have run into all sorts of problems with > various ways of doing it. Rather than recount all those ways and why > they didn't work, I instead present the minimal example of the problem I > am trying to solve and hope that someone can solve it. Rather than try to sort out a way to create methods on the fly, perhaps it would be better if you were to explain what you are trying to do ... what problem does this approach solve? There are any number of ways to produce results for given input data, and creating new methods for a class at runtime is not necessarily the most efficient way to accomplish your goal. What I am saying is you are now struggling to solve, not the original problem your program is meant to solve, but the problems created by your solution. One possible alternative is a hash with keys consisting of identifying labels, and values consisting of lambdas that can produce various kinds of results. The lambdas could easily stand in for your custom methods, and this approach might end up being easier to implement. Example: ---------------------------------------- #!/usr/bin/ruby -w hash = { "+" => lambda { |x,y| x + y }, "-" => lambda { |x,y| x - y }, "*" => lambda { |x,y| x * y }, "/" => lambda { |x,y| x / y }, } puts hash["/"].call(1.0,3.0) ---------------------------------------- Output: 0.333333333333333 Depending on what you are trying to do, this might be easier to use and might be faster as well, especially if you take your development time into account. -- Paul Lutus http://www.arachnoid.com