Skip to content

Instantly share code, notes, and snippets.

@gouthamvel
Created July 4, 2014 04:30
Show Gist options
  • Save gouthamvel/4df64013e9011d2a6fb1 to your computer and use it in GitHub Desktop.
Save gouthamvel/4df64013e9011d2a6fb1 to your computer and use it in GitHub Desktop.
parse string of arithmetic operation and perform the operations
input = "20+4+2-1"
class String
def is_i?
!!(self =~ /\A[0-9]+\z/)
end
end
def operation(op)
case op
when "+" then -> (a, b){a + b}
when "-" then -> (a, b){a - b}
else
p a,b,op
raise "no operation defined"
end
end
tokens = input.split(/(\d*)([-+])/).reject { |e| e.empty? } # => ["2", "+", "4", "+", "2"]
operaions_stack = tokens.map { |token| token.is_i? ? token.to_i : operation(token)} # => array of numbers and lambdas containing the operation to be performed
# inject an empty stack, and when stack size is 3 compute the result and put it back in stack
last_opp = operaions_stack.inject([]) do |mem, var|
mem = [mem.first.(mem[1], mem[2])] if mem.size == 3
if var.is_a? Proc
mem.unshift(var)
else
mem << var
end
end
p last_opp.first.(last_opp[1], last_opp[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment