Note that there are some explanatory texts on larger screens.

plurals
  1. POChange the binding of a Proc in Ruby
    primarykey
    data
    text
    <p>I have this code:</p> <pre><code> l = lambda { a } def some_function a = 1 end </code></pre> <p>I just want to access <code>a</code> by the lambda and a special scope which has defined <code>a</code> already somewhere like inside <code>some_function</code> in the example, or just soon later in the same scope as:</p> <pre><code> l = lambda { a } a = 1 l.call </code></pre> <p>Then I found when calling <code>l</code>, it is still using its own binding but not the new one where it was called.</p> <p>And then I tried to use it as:</p> <pre><code> l.instance_eval do a = 1 call end </code></pre> <p>But this also failed, it is strange that I can't explain why.</p> <p>I know the one of the solution is using <code>eval</code>, in which I could special a binding and executing some code in text, but I really do not want to use as so.</p> <p>And, I know it is able to use a global variable or instance variable. However, actually my code is in a deeper embedded environment, so I don't want to break the completed parts if not quite necessary.</p> <p>I have referred the <code>Proc</code> class in the documentation, and I found a function names <code>binding</code> that referred to the <code>Proc</code>'s context. While the function only provided a way to access its binding but cannot change it, except using <code>Binding#eval</code>. It evaluate text also, which is exactly what I don't like to do.</p> <p>Now the question is, do I have a better (or more elegant) way to implement this? Or using <code>eval</code> is already the <em>regular</em> manner?</p> <p>Edit to reply to @Andrew:<br> Okay, this is a problem which I met when I'm writing a lexical parser, in which I defined a array with fixed-number of items, there including at least a <code>Proc</code> and a regular expression. My purpose is to matching the regular expressions and execute the Procs under my special scope, where the Proce will involved some local variables that should be defined later. And then I met the problem above.<br> Actually I suppose it is not same completely to <a href="https://stackoverflow.com/questions/9245947/is-it-possible-to-access-blocks-scope-in-method/9246066#9246066">that question</a>, as mine is how to pass <em>in</em> binding to a Proc rather than how to pass it <em>out</em>.</p> <p>@Niklas: Got your answer, I think that is what exactly I want. It has solved my problem perfectly.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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