新手问题 如何计算字符串?

RKLNF · March 10, 2013 · Last by luikore replied at March 10, 2013 · 1873 hits

例 str='1+2+3+4' 要想得到 10 的答案该如何操作 谢谢

eval(str)

eval 固然好用,但是比较危险。仅对于你举的这个例子,可以这样做。

str.split("+").inject(0) {|sum, n| sum + n.to_i}  # This line is only for `plus operator'

如果要支持四则运算 + 括号的效果,可以参考我写的一个解析器生成器 rsec 的例子:

https://github.com/luikore/rsec/blob/master/examples/arithmetic.rb

treetop 是流行程度高很多的另一个解析器生成器,它的首页上就有个做四则运算的例子

You need to Sign in before reply, if you don't have an account, please Sign up first.