From: Robert Klemme Date: 2011-05-18T23:54:03+09:00 Subject: Re: Generating Functions in Ruby On Wed, May 18, 2011 at 3:46 PM, Andreas Lundgren wrote: > Hi! > > I'm looking for a construction in Ruby to generate a (big) set of > functions. I need these functions to be class methods and called by > unique names since they are called via an external API. > > As an example, let me create two functions that hard codes an addition > and then uses this in a small test program. > > def FivePlusFour >  return 5+4 > end > > def OnePlusSeven >  return 1+7 > end > > puts("Five + Four is " + FivePlusFour().to_s) > puts("One + Seven is " + OnePlusSeven().to_s) > > > I would like a way to generate the methods in runtime. As an old C- > programmer, I'm looking for something like this: > > # Define a macro > define SUM_TEMPLATE(namn,x,y) \\ > def namn \\ >  return x+y \\ > end > > # Create each function with a one-liner in runtime. > SUM_TEMPLATE(FivePlusFour, 5, 4) > 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 < (Please don't reply how to solve this silly example in a better way, > the true use case is of cause much more complex. But conceptually it's > the same.) Is it really? Do you always have one name and two values as input? Can you give a bit more contextual information? Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/