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
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
Check article out Variable Bindings in Ruby
class Reference
def initialize(var_name, vars)
@getter = eval "lambda { #{var_name} }", vars
@setter = eval "lambda { |v| #{var_name} = v }", vars
end
def value
@getter.call
end
def value=(new_value)
@setter.call(new_value)
end
end
def ref(&block)
Reference.new(block.call, block.binding)
end
def bar(ref)
# magic code goes here, it outputs "a = 100"
p ref.value
end
def foo
a = 100
bar(ref{:a})
end
foo
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. (not in 1.8.X or 1.9.X)
The caller method only returns strings which are of little use. The following code would be a good start for patch that could give you the facility.
There is an additional hacky way to get this going using set_trace_func
but the performance hit would be huge and the solution is very fragile.