0
아래 답변을 이해할 수있는 사람이 있습니까? 나는 다음의 rspec 테스트를 통과하는 것이 올바른 대답이라는 것을 알고있다. 또한 이것을 구현하는 다른/간단한 방법이 있습니까? 나는 그것이 그것을 어떻게하는지 이해하지 못하기 때문에.루비 RPN 계산기 - rspec 테스트
def tokens(string)
string.split.map{|s| s[/\d/] ? s.to_i : s.to_sym}
end
def evaluate(pol)
order = []
opps = {:+ => plus, :- => minus, :/ => divide, :* => times }
tokens(pol).reverse.chunk{|n| n.is_a?(Integer)}.each{|e,a| e == true ? a.reverse.each{|a| push(a) } : a.each {|a| order.push(a) }}
order.reverse.each {|o| (opps[o]) } end
RSpec에 시험이 시험 루비, RSpec에 시험과 사투를 벌인 사람들을 위해
# extra credit
it "tokenizes a string" do
calculator.tokens("1 2 3 * + 4 5 - /").should ==
[1, 2, 3, :*, :+, 4, 5, :-, :/]
end
# extra credit
it "evaluates a string" do
calculator.evaluate("1 2 3 * +").should ==
((2 * 3) + 1)
calculator.evaluate("4 5 -").should ==
(4 - 5)
calculator.evaluate("2 3 /").should ==
(2.0/3.0)
calculator.evaluate("1 2 3 * + 4 5 - /").should ==
(1.0 + (2 * 3))/(4 - 5)
end