Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could raise an exception in the block and catch that exception.</p> <pre><code>module Tester class Breaker &lt; Exception; end class GoodBreak &lt; Breaker; end class BaadBreak &lt; Breaker; end end def test_block(name) begin yield rescue Tester::Breaker=&gt;e case e when Tester::GoodBreak then puts "All is well with #{name}" when Tester::BaadBreak then puts "BAD STUFF WITH #{name}" else raise end end end def good; raise Tester::GoodBreak; end def bad; raise Tester::BaadBreak; end test_block('early out') do good if true good if puts("NEVER SEE THIS") || true bad end test_block('simple pass') do good if false good if puts("SEE THIS FROM PASS TEST") || true bad end test_block('final fail') do good if false good if puts("SEE THIS BUT PUTS IS NIL") bad end #=&gt; All is well with early out #=&gt; SEE THIS FROM PASS TEST #=&gt; All is well with simple pass #=&gt; SEE THIS BUT PUTS IS NIL #=&gt; BAD STUFF WITH final fail </code></pre> <p>Here's another example using <code>throw/catch</code> (thanks @jleedev!) instead of <code>raise/rescue</code> (updated to pass a return value along):</p> <pre><code>def test_block(name) result = catch(:good){ catch(:bad){ yield } } puts "Testing #{name} yielded '#{result}'", "" end def good; throw :good, :good; end def bad; throw :bad, :bad; end test_block('early out') do good if true good if puts("NEVER SEE THIS") || true bad end test_block('simple pass') do good if false good if puts("SEE THIS FROM PASS TEST") || true bad end test_block('final fail') do good if false good if puts("SEE THIS BUT PUTS IS NIL") bad end #=&gt; Testing early out yielded 'good' #=&gt; #=&gt; SEE THIS FROM PASS TEST #=&gt; Testing simple pass yielded 'good' #=&gt; #=&gt; SEE THIS BUT PUTS IS NIL #=&gt; Testing final fail yielded 'bad' </code></pre>
    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. 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