Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>On searching more, I found an answer to at least part of my question:</p> <p>Based on: <a href="http://wikis.onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc/style/print" rel="noreferrer">http://wikis.onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc/style/print</a></p> <p>The rest is from experimentation after Jim Shubert's helpful pointers.</p> <ol> <li>This can be accomplished by <code>eval</code>-ing <code>local_variables</code>, <code>instance_variables</code> and <code>global_variables</code> inside the binding.</li> <li>You can do something as described below, given <code>var_name</code>, <code>new_val</code>, <code>my_binding</code> (syntax may be imperfect or improvable, feel free to suggest in comments. Also, I couldn't get the code formatting to work inside the list, suggestions for how to do that will also be implemented.)</li> <li>You can straightforwardly take (2) and loop the hash to do this.</li> <li>See the second code block below. The idea is to start with TOPLEVEL_BINDING, which I believe normally just includes the global variables.</li> </ol> <p>This does involve using string <code>eval</code>. However, no variable values are ever expanded into the strings involved, so it should be fairly safe if used as described, and should work to 'pass in' complex variable values.</p> <p>Also note that it's always possible to do <code>eval var_name, my_binding</code> to get a variable's value. Note that in all of these uses it's vital that the variable's <em>name</em> be safe to eval, so it should ideally not come from any kind of user input at all.</p> <p>Setting a variable inside a binding given <code>var_name</code>, <code>new_val</code>, <code>my_binding</code>:</p> <pre><code># the assignment to nil in the eval coerces the variable into existence at the outer scope setter = eval "#{var_name} = nil; lambda { |v| #{var_name} = v }", my_binding setter.call(new_val) </code></pre> <p>Building a "bespoke" binding:</p> <pre><code>my_binding = eval "lambda { binding }", TOPLEVEL_BINDING # build a nearly-empty binding # set_in_binding is based on the above snippet vars_to_include.each { |var_name, new_val| set_in_binding(var_name, new_val, my_binding) } </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.
 

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