How to turn strings into local vars to eval them in a proc?

Hey folks,

Here’s a neat little item…

Say I have an array of arrays like this…

[[“var1”, 23], [“var2”, 45], [“var3”, 67]]

I also have a string that describes a math function of those variables,
say, like this…

“var1^2 + var2*3 - var3/34”

How can I iterate through the array of arrays, converting the string
vars into local variables set to their corresponding value so that I can
finally evaluate the whole lot of them in the proc?

func = ->(){eval “var1^2 + var2*3 - var3/34”}

func.call # which gets me my result, yay!

Thanks,

Grar

You mean like this?

23^2 + 45*3 - 67/34 #=> 159

\$VERBOSE = true

func = ->vars{
eval [
* vars.map{|var, val|"#{var} = #{val}"},
“var1^2 + var2*3 - var3/34”
].join("\n")
}

func.call([[“var1”, 23], [“var2”, 45], [“var3”, 67]]) #=> 159

Kenichi K. wrote in post #1046944:

You mean like this?

23^2 + 45*3 - 67/34 #=> 159

\$VERBOSE = true

func = ->vars{
eval [
* vars.map{|var, val|"#{var} = #{val}"},
“var1^2 + var2*3 - var3/34”
].join("\n")
}

func.call([[“var1”, 23], [“var2”, 45], [“var3”, 67]]) #=> 159

That works great, thanks much!

Grar