Ruby evaluate without eval?

后端 未结 5 515
野性不改
野性不改 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:04

    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)

提交回复
热议问题