Vicky Vicky - 3 years ago 43
Ruby Question

Best way to execute math expression string in ruby?

I want to execute math expression which is in string like this sample strings.

  1. A = "23>=34"

  2. B = "77<90"

  3. C = "33>77"

and i want some function like
if exec_string(A)
which should return true or false.

Currently i am using this method

rest = --- # i am splitting the string in to three(L- as left number cmpr- as compare and R- as right number )
def self.calc(L,cmpr,R)
case cmpr
when "<"
if L.to_i < R.to_i
return true

Which could not handle lot of cases. Any help?

Answer Source

You could use eval for that:

#=> false
#=> true

But keep in mind that eval might be evil. Especially if the evaluated string is provided by a user. Imagine what happens if a user enters a command to delete files...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download