From: 7stud -- Date: 2011-05-19T04:44:45+09:00 Subject: Re: Generating Functions in Ruby Robert K. wrote in post #999483: > On Wed, May 18, 2011 at 3:46 PM, Andreas Lundgren > wrote: >> return 5+4 >> I would like a way to generate the methods in runtime. As an old C- >> SUM_TEMPLATE(OnePlusSeven, 1, 7) >> >> # Test program >> puts("Five + Four is " + FivePlusFour().to_s) >> puts("One + Seven is " + OnePlusSeven().to_s) >> >> Is this possible in Ruby? > > def SUM_TEMPLATE(name, x, y) > class < end > >> I need these functions to be class methods ...of what class? Perhaps something like this: def SUM_TEMPLATE(the_class, meth_name, x, y) class_obj = Object.const_get(the_class) class_obj.singleton_class.class_eval do define_method(meth_name) do x + y end end end class Dog end SUM_TEMPLATE('Dog', 'FivePlusFour', 5, 4) puts Dog.FivePlusFour --output:-- 9 -- Posted via http://www.ruby-forum.com/.