I am trying to set a local variable to an existing binding
def foo_callback
lambda { |name| p name }
end
b = foo_callback.binding
The binding doesn’t have any local variables to begin with:
b.eval("local_variables") # => []
Let us set a primitive local variable to the binding:
b.eval("age=30")
Everything works as expected:
b.eval("local_variables") # => ["age"]
b.eval("age") # => 30
Now, let us try to set a non-primitive local variable to the binding:
country = Country.first
b.eval("lambda {|v| country = v}").call(country)
Note: The technique for setting the variable is borrowed from the facet gem. I tried the ruby 1.9 safe implementation with same results.
The binding does not reflect the local variable country.
b.eval("local_variables") # => ["age"]
How do I get around this issue? Essentially, I want to declare a new variable in a binding using the value of an existing, non primitive variable.
I am on Ruby 1.8.7.
You’re creating
countryoutside of the binding, and then thecountryinside thelambdais only valid within that scope. Why notevalit if you need to inject that into the binding as well?Update
Try declaring the variable outside of the scope of the
lambdabut inside the scope of the binding: