Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, <code>block.call()</code> is done with <code>yield</code>, and you don't need the <code>&amp;block</code> parameter that way.</p> <p>You can't normally do what you want, blocks are bound when they are created, and inside the block you can see the local variables defined at that moment; the easiest way to do what you want, which is not how you will use blocks normally, is this:</p> <pre><code>def test() foo = yield if block_given? puts "in test, foo is #{foo}" end test() { foo="this is foo" } </code></pre> <p>But that's only a side effect because <code>foo</code> is "returned" by the block. If you instead do this:</p> <pre><code>def test() foo = yield if block_given? puts "in test, foo is #{foo}" end test() { foo="this is foo" "ha ha, no foo for you" } </code></pre> <p>You'll notice that it does something different.</p> <p>Here's more magic:</p> <pre><code>def test(&amp;block) foo = eval "foo", block.binding puts foo block.call foo = eval "foo", block.binding puts foo end foo = "before test" test() { foo = "after test" "ha ha, no foo for you" } </code></pre> <p>That would kind of work, but it breaks if you remove <code>foo = "before test"</code> because <code>foo</code> becomes a local variable in the block and does not exist in the binding.</p> <p>Summary: you can't access local variables from a block, just the locals where the block was defined and the return value of the block.</p> <p>Even this won't work:</p> <pre><code>def test(&amp;block) eval "foo = 'go fish'", block.binding block.call bar = eval "foo", block.binding puts bar end </code></pre> <p>because the <code>foo</code> in the binding is different from the local in the block (I didn't know this, thanks).</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. 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.
    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