From: Rich Kilmer Date: 2002-07-25T14:09:50+09:00 Subject: RE: A Code Challenge Well...here is some Ruby-fu. It's a bit evil with eval...but it works with both a proc as a parameter or the block class Object def extend_method(meth, proc=nil, &block) proc = block unless proc meth = meth.to_s if meth.kind_of? Symbol self.instance_eval { @___procs___ = {} unless @___procs___ @___procs___[meth]=proc } return if respond_to? "__#{meth}__" instance_eval <<-EOS class << self alias_method :__#{meth}__, :#{meth} def #{meth}(*args) send(:__#{meth}__, *args) @___procs___['#{meth}'].call(*args) end end EOS end end class O def x(a) puts "do something with #{a}" end end o = O.new o.x(1) p1 = Proc.new { |a| puts "do something wonderful with #{a}" } o.extend_method(:x, p1) o.x(2) o.extend_method(:x) { |a| puts "do something sweet with #{a}" } o.x(3) -rich > -----Original Message----- > From: Tom Sawyer [mailto:transami@transami.net] > Sent: Wednesday, July 24, 2002 11:56 PM > To: ruby-talk ML > Subject: A Code Challenge > > Problem: > > given a proc p and an object o with method x, such that the arity of x > and p are the same, dynamically append p into x. > > statically you have this: > > class O > def x(a) > puts "do something with #{a}" > end > end > o = O.new > > then given: > > p = Proc.new { |a| puts "do something else with #{a}" } > > the goal is to dynamically modify instance o such that it were AS IF it > were an instantiation of: > > class O > def x(a) > puts "do something with #{a}" > puts "do something else with #{a}" > end > end > > ~transami >