2008/6/27 Leslie Viljoen <leslieviljoen / gmail.com>:

> Is there a way that methods defined with define_method can take a block?
> Here's my fighting module:
>
> module Taikwando
>        def self.add_warrior(n)
>                define_method(n) do
>                        puts "#{n} fights!"
>                        yield
>                end
>        end
>
>        def fight(*names)
>                names.each do |n|
>                        Taikwando.add_warrior(n)
>                end
>        end
> end
>
> include Taikwando
>
>
>
> ..when I require it, I can do this:
>
>>> fight "morpheus", "neo"
> => ["morpheus", "neo"]
>>> neo do
> ?> puts "karate chop!"
>>> end
> neo fights!
> LocalJumpError: no block given
>        from ./kungfu.rb:102:in `neo'
>        from (irb):5
>
>
> - the yield does not work. Any ideas?

AFAIK there is no way (yet) to define a method that needs a block via
define_method.  I believe you can try to work around this by doing

self.class.class_eval "def #{m}; puts '#{m} fights'; yield; end"

Kind regards

robert


-- 
use.inject do |as, often| as.you_can - without end