Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A short introduction:</p> <p>You don't need the Mod-instance, if you define @@foo outside <code>initialize</code>.</p> <p>You don't need the Mod class to get the problem:</p> <pre><code>class Foo def yielder p 2 yield "hello" end end foo = Foo.new foo.yielder do |hello| puts hello end foo.class.send(:define_method,:yielder) do p 1 yield "new hello" end foo.yielder do |hello| puts hello end </code></pre> <p>You may shorten your example again:</p> <pre><code>class Foo end foo = Foo.new foo.class.send(:define_method,:yielder) do yield "new hello" end foo.yielder do |hello| puts hello end </code></pre> <p>This is the same as:</p> <pre><code>class Foo define_method(:yielder) do yield "new hello" end end foo = Foo.new foo.yielder do |hello| puts hello end </code></pre> <p>End of Introduction.</p> <p>And now, I'm not sure if I understood correct what you want (and if I understand ruby correct ;) ) <code>define_method</code> accepts a block and use it as method body. If the new method should receive a block on its own, you must define it in the interface of the definition and call it:</p> <pre><code>class Foo define_method(:yielder) do | &amp;prc | prc.call("new hello") end end foo = Foo.new foo.yielder do |hello| puts hello end </code></pre> <p>Or the same logic in your example:</p> <pre><code>class Foo def yielder yield "hello" end end class Mod def initialize @@foo = Foo.new end def self.foo @@foo end end worker = Mod.new Mod.foo.yielder do |hello| puts hello end Mod.foo.class.send(:define_method,:yielder) do | &amp;prc | prc.call "new hello" end Mod.foo.yielder do |hello| puts hello end </code></pre> <p>To make the code more robust, I would recommend some checks with <code>block_given?</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload