Ruby没有评估就可以评估吗?

Ruby没有评估就可以评估吗?

问题描述:

如何在不使用eval的情况下评估数学字符串?

How could I evaluate at mathematical string without using eval?

示例:

mathstring = "3+3"

是否可以在不使用评估的情况下进行评估?

Anyway that can be evaluated without using eval?

也许与正则表达式有关??

Maybe something with regex..?

您必须要么eval它,要么对其进行解析;而且由于您不想eval:

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

如果您想实现更复杂的内容,则可以使用RubyParser(如@LBg写道

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