Search code examples
ruby

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 )
    class_name.calc(rest[0],rest[1],rest[2])
    def self.calc(L,cmpr,R)
        case cmpr
          when "<"
            if L.to_i < R.to_i
              return true
            end
           ....
           ....
           ....
         end
    end 

Which could not handle lot of cases. Any help?


Solution

  • You can use eval for that:

    eval("23>=34")
    #=> false
    
    eval("23<=34")
    #=> true
    

    Warning: Keep in mind that using eval is dangerous. Especially when the evaluated string is provided by a user. Imagine what happens if the user passes a command to delete files, instead of a simple number comparison.