From: Chuck Remes Date: 2011-12-04T06:44:58+09:00 Subject: Re: help with recursive method def'n using eval On Dec 3, 2011, at 3:31 PM, Chuck Remes wrote: > I would like to solve a problem where a writer of a class can provide an array of fields and those fields are turned into two things. > > 1. A method called #each_"field_name" that iterates over all of the values in that field. > > 2. A method called #each_combination that defines a series of nested called to #each_"field_name" and at the inside yields a combination of the parameters. [snip] > Given the details above, I would like to produce a method like this: > > def each_combination(&blk) > each_dollars do |dollars| > each_activation_time do |activation_time| > each_personnel_count do |personnel_count| > yield(dollars, activation_time, personnel_count) > end > end > end > end I should have waited a few more minutes. After typing this up, I was hit by inspiration. Here is my solution. def self.create_combination(mod, fields) processed = [] string = "def each_combination(&blk)\n" fields.each_with_index do |field_name, index| string << (" " * (index + 1)) + "each_#{field_name} do |#{field_name}|\n" processed << field_name end string << (" " * (processed.size + 1)) + "yield(#{processed.join(', ')})\n" processed.size.downto(1) { |i| string << (" " * i) + "end\n" } puts string end It's a bit messy (I do extra work so that the method is formatted correctly for the call to #puts), but it produces exactly what I need. I hope this is helpful to someone else too. cr