Вопрос

In Ruby-on-rails, I am receiving input from a call to a XL macro(currently hard coded), which places a mathematical expression in the spreadsheet. If I call the macro I will receive a worksheet with an expression like this in one of the cells

x + ( 3 / 12) 

In the R-O-R application I wish to take this expression and evaluate for different values of x.

row.each do |row|
   y = row
end

I want to find the value of y for say example x = 2 ? Should I receive this expression as a literal ?

Это было полезно?

Решение 2

eval and gsub will get you most of the way there. Fire up irb:

(533)⚡️ irb
2.1.2 :001 > exp = 'x + (3 / 12)'
 => "x + (3 / 12)" 
2.1.2 :002 > eval(exp.gsub(/x/, '25'))
 => 25 
2.1.2 :003 > exp = 'x + (4.0 / 25.0) + 4'
 => "x + (4.0 / 25.0) + 4" 
2.1.2 :004 > eval(exp.gsub(/x/, '25'))
 => 29.16 

Notice the result of command 002. Ruby is assuming the 3 / 12 is integer math, so the result will be an integer, which is 0 in this case. In 003 floating point math occurs because the numbers are decimals. This aspect may be an issue you need to tackle more creatively, or just make sure your expressions conform to the type of math you need to occur.

Be aware of the security concerns with eval, you're executing Ruby code in there, so mean people may put mean things in there to try and execute it.

Другие советы

There is no built-in function to do this securely. You need a math parser and evaluator. You can write one yourself or you could use an existing one like Dentaku.

Why not write a one line function, as following:

def foo(x) x + (3 / 12) end

Now you can use this to calculate any value of x, for x = 2, you can do: foo(2) or foo 2.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top