From: Tom Sawyer Date: 2002-07-26T01:33:53+09:00 Subject: Re: A Code Challenge THANKS YOU ALL FOR PARTICIPATING! SOME COOL CODE! paul. i think i'll give you the prize $ cha-ching ;-) your solution is the overall best i think. rich's and the lucky stiff's were definite feats and took some extra things into consideration which was nice: arity error checking for instance. and ned's was amazingly short and sweet --good for toplevel execution. but yours is small and versitle and is much like what i finally worked out myself, only i kept it external from the object: m = o.method(:x) # get the object method mod = Module.new # make a module with redefined method mod.module_eval { define_method(:x) { |*args| m.call(*args) p.call(*args) } } o.extend mod # extend object i wonder how send vs. module_eval compare? thanks everyone. hope it was a fun and educational. ~transami On Thu, 2002-07-25 at 08:25, Paul Brannan wrote: > I will first answer your question with a question: > > *** WHY!?! *** > > But here's a solution, just for fun (based off the same idea as > [ruby-talk:29122]): > > class Object > def append_to_method(method_name, p) > m = method(:x) > mod = Module.new > mod.send(:define_method, :x) do |*args| > m.call(*args) > p.call(*args) > end > extend(mod) > end > end > > class O > def x(a) > puts "do something with #{a}" > end > end > > o = O.new > p = Proc.new { |a| puts "do something else with #{a}" } > o.append_to_method(:x, p) > o.x("foo") > > The only disadvantage I can think of is that if x takes a block, you can > now no longer pass it a block. I figure this probably isn't a problem > anyway since you are appending a proc to it, which cannot take a block. > > Paul > > -- ~transami