# Recursive method definition -- A Metaprogramming problem?

**URL:** <https://www.ruby-forum.com/t/recursive-method-definition-a-metaprogramming-problem/131724>\
**Category:** Ruby\
**Created:** [March 12, 2008, 7:20pm UTC](https://www.ruby-forum.com/t/recursive-method-definition-a-metaprogramming-problem/131724 "2008-03-12T19:20:43Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![DMisener](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c57346/32.png) [@DMisener](https://www.ruby-forum.com/u/DMisener)\
**Post date:** [March 12, 2008, 7:20pm UTC](https://www.ruby-forum.com/t/recursive-method-definition-a-metaprogramming-problem/131724/1 "2008-03-12T19:20:43Z")

</div>

Any hints on how to imbed _redefine\_method_’s _payload_ as a block  
instead of a \*nasty" eval string?  
(see example below)

# How support payload being a block??

def redefine\_method method,payload # using previous definition of  
itself  
class\_eval %[  
alias old\_#{method} #{method}  
def #{method}(\*args,&block)  
alias new\_#{method} #{method}  
def #{method}(\*args,&block); old\_#{method}(\*args,&block)  
end  
#{payload}  
def #{method}(\*args,&block); new\_#{method}(\*args,&block)  
end  
end  
]  
end

This is useful when redefining a new method using existing code which  
uses the “prior” definition’s implementation.

Example usage:

class FS\_TransactionsFile \< PA\_TransactionsFile  
redefine\_method :each,%[filter(proc{|\_| %w[LW KS].member? _.fcode})  
{|_| yield \_}]  
end

where FS\_TransactionFile implements the _filter_ method using a  
possibly similarly redefined definition of _each_ (for  
PA\_TransactionFile).

The above works – but seems clumsy.

FYI: Filter in above example is currently implemented as:

class Object # combination of Select/Map functionality  
def filter owncode=nil,keep\_original=true  
# _keep\_original_ is the content value used to mean return the  
original item  
# i.e. if keep\_original=true and the select routine returns  
true then  
# the original value will be added to result/yielded.  
owncode||=proc{|\_| \_} # default mapping is ‘identity’ i.e.  
same as find\_all  
result=[] # used to collect resulting items if block not  
given  
each do |item|  
if \_=owncode.call(item) # nil items are discarded  
\_=item if \_==keep\_original  
if block\_given?  
yield \_  
else  
result \<\< \_  
end  
end  
end  
result  
end  
end
