5

evalを使用せずに数学文字列を評価するにはどうすればよいですか?

例:

mathstring = "3+3"

とにかく、evalを使わずに評価できますか?

多分正規表現で何か..?

4

5 に答える 5

7

evalまたはそれを解析するか、解析する必要があります。そして、あなたがしたくないので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がここに書いたように-他の回答も見ることができます)

于 2013-04-13T23:52:18.623 に答える
3

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
于 2013-04-14T00:01:04.693 に答える
1

You have 3 options:

  1. In my honest opinion best - parse it to Reverse Polish Notation and then parse it as equation
  2. As you say use RegExps
  3. Fastest, but dangerous and by calling eval but not Kernel#eval

    RubyVM::InstructionSequence.new(mathstring).eval
    
于 2013-04-14T00:01:30.063 に答える
0

Sure--you'd just want to somehow parse the expression using something other than the bare Ruby interpreter.

There appear to be some good options here: https://www.ruby-toolbox.com/search?q=math

Alternatively, it probably wouldn't be that hard to write your own parser. (Not that I've seriously tried--I could be totally full of crap.)

于 2013-04-13T23:46:59.470 に答える
0

Dentakuは (私はまだ使用していませんが) 良い解決策のように思えます - (数学的および論理的な) 式をチェックし、それらを評価することができます。

calculator = Dentaku::Calculator.new
calculator.evaluate('kiwi + 5', kiwi: 2)
于 2016-03-14T19:33:56.800 に答える