Essentially I'm wondering if the following can be done in Ruby.
So for example:
def bar(symbol) # magic code goes here, it outputs "a = 100" end def foo a = 100 bar(:a) end
Ruby's eval takes in a string as the argument, which means that it is possible for one to accept user input or read code off of a file and get it evaluated from within your program - essentially re-programming the way your program behaves.
A Context is something that can hold modules, classes, methods, attributes, aliases, requires, and includes. Classes, modules, and files are all Contexts.
You have to pass foo
's context to bar
:
def foo a = 100 bar(:a, binding) end def bar(sym, b) puts "#{sym} is #{eval(sym.to_s, b)}" end
There is no built-in way to get a callers binding in Ruby in 1.8.X or 1.9.X.
You can use https://github.com/banister/binding_of_caller to work around.
In MRI 2.0 you can use RubyVM::DebugInspector, see: https://github.com/banister/binding_of_caller/blob/master/lib/binding_of_caller/mri2.rb
Working sample in MRI 2.0:
require 'debug_inspector' def bar(symbol) RubyVM::DebugInspector.open do |inspector| val = eval(symbol.to_s, inspector.frame_binding(2)) puts "#{symbol}: #{val}" end end def foo a = 100 bar(:a) end foo # a: 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With