thanksĄ¤ I use your example in irb:

module Kernel

   define_method(:foo) { yield 1}

end

no error, but if I invoke it:

Kernel.foo { 2 }

the error jumps,

LocalJumpError: no block given

howeverĄ¤ this is OK

module Kernel

   define_method(:foo) { 1 }

end

It seems I can not use yield in define_method, can you tell me more details?





Robert Klemme wrote in post #1079864:
> On Mon, Oct 15, 2012 at 8:37 AM, li shoubo <lists / ruby-forum.com> wrote:
>
>> please help me to figure out why I can not use the first solution.
>
> You simply cannot define methods which use block passed to them via
> define_method as you have found out.  Minimalistic example:
>
> $ ruby -e 'module Kernel;def foo; yield 1 end end; foo {|x| p x}'
> 1
> $ ruby -e 'module Kernel;define_method(foo) { yield 1 };end;foo {|x| p
> x}'
> -e:1:in `<module:Kernel>': undefined local variable or method `foo'
> for Kernel:Module (NameError)
>         from -e:1:in `<main>'
>
> Another variant is to use class_eval:
>
> $ ruby -e 'Kernel.class_eval "def foo; yield 1 end";foo {|x| p x}'
> 1
>
> Kind regards
>
> robert