From: theschof@... (TheSchof) Date: 2002-01-19T08:19:18+09:00 Subject: Re: dynamic method creation "Albert L. Wagner" alwagner@uark.edu wrote: >I have a need to dynamically create methods with method names >that are not known until run time. Someone already mentioned this, but instance_eval really is your best bet for actually creating methods. The advantage of it is that when you combine that with ruby's sophisticated string interpolation you can get code which will look very close to how it will appear. But you have to be comfortable with string interpolation if you are going to be dealing with strings inside of this which also will need to undergo interpolation. I had this a while back when I was working on a ruby-java bridge via via Tcl-blend-- it wasn't as complicated as it sounds. But it had a JObject class which took in a string as the fully-qualified name of a Java class, and then used tclblends reflection capabilites to grab a list of the methods for that class, and declare them for each instance like so: instance_eval "def #{met} (*args) if block_given? yield \"#{met}\", @tclhandle, args else $tcl.eval \"#{@tclhandle} #{met} #\{args.join ' '}\" end end" I was getting excited about this but I started to realize that maybe creating methods was the wrong approach and method_missing would have been better and provided more encapsulation in case a Ruby object had the same method name as a java object. If you're reading in strings you could intern them, use them as the keys for a hash table and compose Proc objects for their values. Use method_missing to catch them and just look up the symbol in the hashtable and call its Proc object (passing along any arguments). I was starting to think along those lines myself but then Jan Arne Petersen released a really fantastic JRuby interpreter, and no one had expressed any interest in my fledgeling project so I abandoned it and can't tell you from experience how well this would work in practice, but I can't think of a fault in the theory right now. HTH, Alexander Schofield