From: Joel VanderWerf Date: 2004-03-25T06:33:19+09:00 Subject: Re: Dynamically define method rolo wrote: > > I need something like this > > def on_success(&block) > @event['success'] = block > end > > I want the above method to be defined dynamically > > def define_my_method(symbol) > .... > ... > .... > .... > end > > any call to define_my_method(:success) should result in > > def on_success(&block) > @event['success'] = block > end > > and will be used as > > myobject.on_success(){ > p "Success" > } > I tried using define_method but am having problems in passing a block. I think that's just a limitation of define_method--you can define a method with a specified a parameter list, but not with the ability to receive a block. The first example below is the best I could come up with using define_method--you've probably gotten this far as well. The second example works as you want (AFAIU), but uses class_eval. =============== class C def self.define_my_method(symbol) define_method("on_#{symbol}") do |handler| @event ||= {} @event[symbol] = handler # Proc.new fails end end define_my_method "success" define_my_method "failure" def handle(condition) @event[condition].call end end c = C.new c.on_success(proc { puts "handled success" }) c.on_failure(proc { puts "handled failure" }) c.handle("success") c.handle("failure") =============== =============== class C def self.define_my_method(symbol) # should check that symbol is legit class_eval %{ def on_#{symbol}(&handler) @event ||= {} @event["#{symbol}"] = handler end } end define_my_method "success" define_my_method "failure" def handle(condition) @event[condition].call end end c = C.new c.on_success do puts "handled success" end c.on_failure do puts "handled failure" end c.handle("success") c.handle("failure") =================