Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby evaluate without eval?

Tags:

ruby

eval

How could I evaluate at mathematical string without using eval?

Example:

mathstring = "3+3"

Anyway that can be evaluated without using eval?

Maybe something with regex..?

like image 321
Tommy Avatar asked Apr 13 '13 23:04

Tommy


2 Answers

You must either or eval it, or parse it; and since you don't want to eval:

mathstring = '3+3'
i, op, j = mathstring.scan(/(\d+)([+\-*\/])(\d+)/)[0] #=> ["3", "+", "3"]
i.to_i.send op, j.to_i #=> 6

If you want to implement more complex stuff you could use RubyParser (as @LBg wrote here - you could look at other answers too)

like image 192
mdesantis Avatar answered Sep 30 '22 10:09

mdesantis


I'm assuming you don't want to use eval because of security reasons, and it is indeed very hard to properly sanitize input for eval, but for simple mathematical expressions perhaps you could just check that it only includes mathematical operators and numbers?

mathstring = "3+3"
puts mathstring[/\A[\d+\-*\/=. ]+\z/] ? eval(mathstring) : "Invalid expression"
=> 6
like image 40
user21033168 Avatar answered Sep 30 '22 12:09

user21033168