Note that there are some explanatory texts on larger screens.

plurals
  1. POEarly return from a block given to instance_exec
    primarykey
    data
    text
    <p>I need to allow blocks to be defined and called within the scope of a class, using <code>instance_exec</code> (via Rails 2.3.2). However, some of these blocks need to return early in some situations, which is causing me a problem.</p> <p>My application was built using ruby 1.8.6, but I need to get it running on 1.8.7 as well. It seems that between the two versions the ability to return from within a lambda was removed. The following works in 1.8.6, but throws a <code>LocalJumpError</code> (unexpected return) in 1.8.7:</p> <pre><code>class Foo def square(n) n ** 2 end def cube(n) n ** 3 end def call_block(*args, &amp;block) instance_exec *args, &amp;block end end block = lambda { |n| return square(n) if n &lt; 5 cube(n) } f = Foo.new f.call_block(5, &amp;block) # returns 125 f.call_block(3, &amp;block) # returns 9 in 1.8.6, throws a LocalJumpError in 1.8.7 </code></pre> <p>I determined that I could get it working in 1.8.7 if I replaced <code>return</code> in my block with <code>next</code>, but <code>next square(n) if n &lt; 5</code> results in <code>nil</code> in 1.8.6.</p> <p>Is there any way I can get this working in both 1.8.6 and 1.8.7? I know that I can restructure my blocks to use branching instead of an early return, but some blocks are more complex and have multiple situations where an early return is needed.</p> <p>Also, is this going to change further if I want to get my code running in ruby 1.9?</p> <p><strong>Edit:</strong> I've discovered that the reason it works in 1.8.6 and not 1.8.7 is that 1.8.7 defines its own <code>instance_exec</code> in the C source, while 1.8.6 uses Rails' implementation. If I override <code>instance_exec</code> in 1.8.7 with Rails' version, it works there too.</p>
    singulars
    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. 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