Ruby evaluate without eval?

后端 未结 5 477
野性不改
野性不改 2021-01-19 14:32

How could I evaluate at mathematical string without using eval?

Example:

mathstring = \"3+3\"

Anyway that can be evaluated without

5条回答
  •  礼貌的吻别
    2021-01-19 15:06

    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
    

提交回复
热议问题