Just an idea which may come in handy. Can this be done and how in Ruby.
def calc(what)
some_eval(what)
end
a=10
b=12
calc(‘a+b’) # expression as parameters
=> 12 # would return
a=‘aa’
b=‘bb’
calc(‘a+b’)
=> ‘aabb’
This is of course strictly hypothetical. I would like the expression to
be evaluated inside the method using variables which are local to the
calling part.
This is of course strictly hypothetical. I would like the expression to
be evaluated inside the method using variables which are local to the
calling part.
As has been demonstrated you need the binding of the context in which
you want to evaluate your expression string. I see two options.
explicitly, i.e.
def calc(what, bind)
eval(what, bind)
end
but this is pointless as “calc” is just an alias for “eval”.
implicitly
You can keep track of bindings by implementing a trace function (see
set_trace_func). Argument 4 is the current binding and you can place
them in a thread local stack, e.g.
untested
set_trace_func lambda {|*a|
case a.first
when /call$/
(Thread.current[:bindings] ||= []).push(a[4])
when /return$/
Thread.current[:bindings].pop
end
}
def calc(s)
eval(s, Thread.current[:bindings][-2])
end
Kind regards
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.