From: Ken Bloom Date: 2007-05-12T02:10:32+09:00 Subject: Re: Creating and adding new methods in runtime On Fri, 11 May 2007 08:06:54 -0700, konryd wrote: > Hello, I need to add in runtime several methods to my class. How can I > accomplish this in ruby? > More precisely: I need my class to overload arithmetic operators with > fixnums in both ways (4+MyClass, MyClass+4). All the necessary info is > stored in a hash, so I created a method to do all the stuff. It looks > like do_operation(operator, other) > But still I have to add every single operator overloader: class Fixnum > > def doo_operation(operator, other) > #...nevermind... > end > > def +(other) > do_operation(:+, other) > end > def -(other) > do_operation(:-, other) > end > end > > can I automate it somehow? Just overrode MyClass#coerce, and the numeric operators on other classes will call coerce if they can't identify the class you're trying to perform arithmetic. Make sure there are +,-, etc... operators on MyClass, and make sure that they (a) handle built-in numeric types (b) handle MyClass+MyClass (c) call coerce if they don't recognize the class on the right-hand side There's more discussion of #coerce in PickAxe. --Ken -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/