2

文字列に数式がある場合x = y + (10/2) * 6(動的であるため、必ずしもそうとは限りません)、それはわかっていx = 5ます。の値を計算するにはどうすればよいyですか?

4

3 に答える 3

3

dentakuのようなパーサーを使用できます

require 'dentaku'

calculator = Dentaku::Calculator.new
calculator.evaluate('10 * 2')
# => 20
calculator.evaluate('kiwi + 5', :kiwi => 2)
# => 7
于 2013-11-10T19:28:41.740 に答える
1

あなたは微積分を使うことができます

001:0> require 'calculus'
true
002:0> exp = Calculus::Expression.new("2 + 3 * x")
#<Expression:f46e77a9377ed2d5a9da768496a7e1c20be51bfe postfix_notation=[2, 3, "x", :mul, :plus] variables={"x"=>nil}>
003:0> exp.postfix_notation
[2, 3, "x", :mul, :plus]
004:0> exp.abstract_syntax_tree
[:plus, 2, [:mul, 3, "x"]]
005:0> exp.variables
["x"]
006:0> exp.unbound_variables
["x"]
007:0> exp["x"] = 5
5
008:0> exp.unbound_variables
[]
009:0> exp.calculate
17
于 2013-11-10T19:40:04.163 に答える