Sandro Paganotti
6/27/2008 12:05:00 PM
[Note: parts of this message were removed to make it a legal post.]
I've re-arranged a bit your code... maybe this way can be more nice-looking:
module Taikwando
def self.add_warrior(n)
define_method(n) do |blk|
puts "#{n} fights!"
blk.call
end
end
def fight(*names)
names.each do |n|
Taikwando.add_warrior(n)
end
end
def moves (fighter,&block)
self.send(fighter,block)
end
end
include Taikwando
fight "morpheus", "neo"
moves("neo") do
puts "karate chop!"
end
On Fri, Jun 27, 2008 at 11:48 AM, Leslie Viljoen <leslieviljoen@gmail.com>
wrote:
> On 6/27/08, Robert Klemme <shortcutter@googlemail.com> wrote:
> > 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
> >
>
> I can explicitly pass a block to my fight method too, but it's so ugly:
> neo(lambda do
> puts "flying kick"
> end
> )
>
>
>
>
> >
> > --
> > use.inject do |as, often| as.you_can - without end
> >
> >
>
>
> --
> [we need your code-fu] : www.zadic.co.za
>
>
--
Dan Quayle - "It's time for the human race to enter the solar system."