For those struggling with this Test Ruby, rspec test, I've managed to breakdown the method above and understand it as below:
Step 1
1. Define operators as procs
Step 2
2. Utilize Token method to generate the following token = [1, 2, 3, :*, :+]
Step 3
3. Check if integer and chunk accordingly
Step 4
4. Check result after chunking, and value of @stack
# ==> [true, [1,2,3]] / @stack = [1, 2, 3]
# ==> [false, [:*, *+]] @stack = [1, 2, 3 * +]
Step 5
5. When reaching an operator, the appropriate method is called
# Calls times -> @stack.push(@stack.pop * @stack.pop)
# (3 * 2)
# Calls plus -> @stack.push(@stack.pop + @stack.pop)
Rspec test should pass now
(3 * 2) + 1
Method after editing
def evaluate(pol)
@stack = []
opps = {
:+ => Proc.new {plus},
:- => Proc.new{minus},
:/ => Proc.new{divide},
:* => Proc.new{times}
}
tokens(pol).chunk{|n| n.is_a?(Integer)}.each do |condition, chunk|
if condition == true
chunk.each{|a| push(a) }
else
chunk.each {|o| (opps[o].call)}
end
end
@stack[0]
end